How to Use Static Variables in JavaScript Classes?

Estimated read time 1 min read

In JavaScript, you can define a static variable in a class using the static keyword. A static variable belongs to the class, rather than to an instance of the class. Here’s an example:

class User {
  static counter = 0;

  constructor(name) { = name;

let user1 = new User("John");
let user2 = new User("Jane");

console.log(User.counter); // Output: 2

In the example above, we define a static variable counter using the static keyword. When we create instances of User, we increment the counter variable. Since the variable is attached to the class, it remains the same across all instances, giving the appearance of a static variable.

Static variables are commonly used for counting the number of instances of a class, or for storing values that are shared across all instances of a class.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply