This post will describe the static variables in JavaScript.
Static Variables in JavaScript
Use the “static” keyword to create a static function or a variable. The static variables have a global scope and are initialized during runtime. They are accessible throughout the entire script with the help of the class name. Use the “this” keyword to invoke a static method or a variable within a static method.
Syntax
The static variable is declared using the following syntax:
Example 1:
Create a class named “MyExampleClass” with a static variable “a” and a static method “exampleMethod()” that will return a string:
static a = 'Welcome To Linuxhint';
static exampleMethod() {
return 'Static variable in JavaScript';
}
}
Outside the class, print the static variable and call the static method with the class name using the “console.log()” method:
console.log("The value returned by static method: "+ MyExampleClass.exampleMethod());
The output displays the value of the static variable and the returned value of the static method:
Example 2:
In the following example, call the static variable in a static method using the “this” keyword:
static a = 'Welcome To Linuxhint';
static exampleMethod() {
return this.a;
}
}
Output
Conclusion
In JavaScript, the static variables and functions are created using the “static” keyword. It is the property of an object that is used by the class itself instead of its instances. It will have a single static value and is initialized during runtime. For calling the static variables, there is no need to create an instance or an object of the class because it will be called using the class name. The static variables are called within a static method, using the “this” keyword. In this post, we described the JavaScript static variables and how to access them.