Ask a Question

Variable declaration in a javascript class


Variable declaration in a javascript class



Can we declare global variables within a javascipt class, outside a function? When I try to declare a variable, it gives error: Syntax Error: Unexpected identifier

Sample code:

class Test {

var abc; //received above error

var abc = "Test"; //received above error

let def; //received above error

function1() {

//some code here

var abcd = "New"; //works fine here



Please suggest how I can create variables outside the functions in this scenario. Thanks!


Esteemed Contributor

This syntax is not allowed in ES6 JavaScript.


This is not a TestComplete restriction but a restriction in the JavaScript language itself.  To declare a variable within a class, it needs to be a property of the class or, as you did so, scoped within a method in the class.  It's all about scoping and variables are not supported in the scope definition of a class.

Robert Martin
[Hall of Fame]
Please consider giving a Kudo if I write good stuff

Why automate?  I do automated testing because there's only so much a human being can do and remain healthy.  Sleep is a requirement.  So, while people sleep, automation that I create does what I've described above in order to make sure that nothing gets past the final defense of the testing group.
I love good food, good books, good friends, and good fun.

Mysterious Gremlin Master
Vegas Thrill Rider
Extensions available

Thanks for your response.

Showing results for 
Search instead for 
Did you mean: