How to use JavaScript Static Variable – Complete Guide

One powerful feature of JavaScript is static variables, which can be used to store values that are shared across multiple instances of a class or function.

In this article, we will explore how to use JavaScript static variables effectively, providing you with the knowledge and skills to take your programming abilities to the next level.

What is a static variable in JavaScript?

In JavaScript, a static variable is a type of variable that belongs to a class or a function rather than an instance of the class.

Unlike regular variables, which are instantiated each time a new object is created, static variables maintain their value across multiple instances.

This means that all instances of a class or invocations of a function share the same static variable.

Example Program for JavaScript Static Variable

To declare a JavaScript static variable, you can use the static keyword within the class definition.

Let’s consider an example of a Person class with a static variable totalPersons that keeps track of the total number of person objects created:

class Person {
  static totalPersons = 0;

  constructor(name) {
    this.name = name;
    Person.totalPersons++;
  }
}

In the above code snippet, the totalPersons variable is declared as static using the static keyword. Each time a new Person object is created, the constructor increments the totalPersons variable, keeping a count of the total number of person objects.

To access the static variable, you can use the class name followed by the dot notation:

console.log(Person.totalPersons); // Output: 0

const person1 = new Person("Alice");
console.log(Person.totalPersons); // Output: 1

const person2 = new Person("Bob");
console.log(Person.totalPersons); // Output: 2

In the above example, we create two instances of the Person class and access the totalPersons variable using the class name. Each time a new instance is created, the static variable is incremented accordingly

How to use static variable in JavaScript?

Here are the things you need to know to use static variables in JavaScript.

1. Declaring a Static Variable

To declare a static variable in JavaScript, you need to use the static keyword followed by the variable name.

Let’s consider an example of a class called Counter that keeps track of the number of instances created:

class Counter {
  static count = 0;

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

In the example above, we declare a static variable count within the Counter class. Each time a new instance of Counter is created, the constructor increments the value of count by one.

2. Accessing Static Variables

To access a static variable, you can use either the class name or an instance of the class.

Let’s see how we can retrieve the value of the count variable from our Counter class:

console.log(Counter.count); // Output: 0

const counter1 = new Counter();
console.log(counter1.count); // Output: undefined

console.log(Counter.count); // Output: 1

As shown in the example, we can access the static variable count using Counter.count.

However, when trying to access the variable through an instance of the class, such as counter1.count, we get undefined.

This is because static variables belong to the class itself, not to the instances.

3. Modifying Static Variables

Static variables can be modified in a similar way to regular variables.

Let’s take our Counter class example and add a method to increment the value of count:

class Counter {
  static count = 0;

  constructor() {
    Counter.count++;
  }

  static incrementCount() {
    Counter.count++;
  }
}

In the modified version of the Counter class, we introduced a static method called incrementCount(), which increments the value of count by one.

We can invoke this method directly on the class itself:

console.log(Counter.count); // Output: 0

Counter.incrementCount();
console.log(Counter.count); // Output: 1

const counter1 = new Counter();
console.log(Counter.count); // Output: 2

As demonstrated, calling the incrementCount() method increases the value of count by one. This change is reflected across all instances of the class.

Static Variables vs. Instance Variables

Static variables and instance variables serve different purposes in JavaScript.

While static variables are associated with the class itself, instance variables are unique to each object or instance of the class.

Here are a few important distinctions between static variables and instance variables:

Static VariablesInstance Variables
Associated with the class itselfAssociated with each instance of the class
Shared among all instancesUnique to each instance
Declared using the static keywordDeclared within the class but outside of any class methods
Accessed using the class nameAccessed using the object or instance of the class
Memory is allocated only once for all instancesMemory is allocated for each instance independently
Useful for maintaining shared data and managing resourcesUseful for storing instance-specific data

Browser compatibility

In JavaScript, there is no issue with browser compatibility when it comes to using static variables. The concept of static variables is supported by all modern browsers and versions that support JavaScript.

Best practices

To make the most of JavaScript static variables, consider the following best practices:

Encapsulation: Ensure that the static variable is declared within the appropriate scope to encapsulate its usage. This helps maintain code organization and prevents unintended access.

Initialization: Assign an initial value to the static variable to define its default state. This ensures predictable behavior and avoids potential issues caused by uninitialized variables.

Naming Conventions: Use descriptive names for static variables to enhance code readability and make their purpose clear. Avoid using generic or ambiguous names that may cause confusion.

Benefits of Using JavaScript Static Variables

JavaScript static variables offer several benefits in the development process. Some of the key advantages include:

  • Shared State: Static variables allow sharing state across different instances or invocations, enabling data persistence and synchronization.

  • Memory Efficiency: Since static variables are shared among instances, they consume less memory compared to regular variables that are instantiated separately.

  • Global Accessibility: Static variables can be accessed globally within a class or function, providing convenient access to shared data without the need for passing variables between functions.

Here are additional resources you can check out to help you master JavaScript.

Frequently Asked Questions

What is static variable in class JavaScript?

A static variable, or static property, in JavaScript is a property that belongs to the class itself rather than an instance of the class.

This means that all instances of the class share the same value for the static property.

Can static variables be accessed without creating an instance of a class?

Yes, static variables can be accessed directly using the class name without creating an instance.

Conclusion

In conclusion, JavaScript static variables provide a powerful tool for managing shared state and accessing data across multiple instances or invocations.

By understanding their features and best practices, you can harness the benefits they offer in your programming endeavors.

Remember to use them judiciously and consider the specific requirements of your application.

Quick step-by-step summary (click to expand)
  1. What is a static variable in JavaScript. Read the ‘What is a static variable in JavaScript?’ section for the details and code.
  2. How to use static variable in JavaScript. Read the ‘How to use static variable in JavaScript?’ section for the details and code.
  3. Static Variables vs. Instance Variables. Read the ‘Static Variables vs. Instance Variables’ section for the details and code.
  4. Browser compatibility. Read the ‘Browser compatibility’ section for the details and code.
  5. Best practices. Read the ‘Best practices’ section for the details and code.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Glay Eliver


Programmer & Technical Writer at PIES IT Solution

Glay Eliver is a programmer and writer at PIES IT Solution, author of over 600 tutorials at itsourcecode.com. Specializes in JavaScript tutorials, Microsoft Office how-tos (Excel, Word, PowerPoint), and Python error debugging covering ImportError, TypeError, AttributeError, ModuleNotFoundError, and JavaScript ReferenceError. Authored several of the site’s highest-traffic Excel and MS Office reference articles.

Expertise: JavaScript · MS Excel · MS Word · MS PowerPoint · Python · Python ImportError · Python TypeError · Python AttributeError · ModuleNotFoundError · JavaScript ReferenceError · Pygame
 · View all posts by Glay Eliver →

Leave a Comment