How to Use Static Variables in JavaScript (w3schools)?

Estimated read time 1 min read

In JavaScript, you can create a static variable by declaring it within a class. A static variable is a variable that is shared among all instances of a class, rather than being unique to each instance.

Here’s an example of how to use a static variable in JavaScript:

class Counter {
  static count = 0;

  increment() {
    Counter.count++;
  }
}

const counter1 = new Counter();
const counter2 = new Counter();

counter1.increment();
console.log(Counter.count); // 1
counter2.increment();
console.log(Counter.count); // 2

In this example, the Counter class has a static variable named count that is shared by all instances of the class. The increment method increments the value of the count variable. When you create instances of the Counter class, they all share the same count variable, so when you call counter1.increment(), the value of count is incremented, and the change is reflected in counter2 as well.

Static variables are useful when you want to maintain state that is shared across all instances of a class, rather than being unique to each instance.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply