JavaScript

Static Variables in JavaScript

A static variable is a class property used by the class itself rather than by any instances of the class. The static variable is declared using the “static” keyword. It will have a single static value that is set during initialization. In JavaScript, a static variable is created to avoid duplication, it is useful for caches and fixed configuration.

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:

static var;

Example 1:
Create a class named “MyExampleClass” with a static variable “a” and a static method “exampleMethod()” that will return a string:

class MyExampleClass {
 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 of static variable: "+ MyExampleClass.a);
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:

class MyExampleClass {
 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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.