I’m trying to understand how to use JavaScript static variables. Is there a way to define variables that retain their values across function calls or are shared among instances of a class in JavaScript? How can I achieve this functionality?
Been working with JavaScript for over a decade now, and if you’re diving into javascript static variables, using static
inside classes is probably the cleanest and most intuitive route.
class Counter {
static count = 0;
increment() {
Counter.count++;
return Counter.count;
}
}
Here, count
is a class-level variable, shared across all instances. No matter how many times you instantiate Counter
, they all access the same static count
. It’s like a shared memory space across all class instances—classic static behavior!"
Yeah, @prynka.chatterjee’s right—that class approach is super straightforward. But I’ve often needed javascript static variables outside of class-based structures. In those cases, closures are a lifesaver.
const counter = (function () {
let count = 0;
return function () {
count++;
return count;
};
})();
With this setup, count
is tucked away inside the closure—acting just like a static variable. Every call to counter()
increases the same hidden value. It’s perfect when you need persistent state but don’t want to mess with globals or create a whole class structure.
Totally agree with both of you! But sometimes I prefer a third approach—attaching the variable directly to the function. Been using this for years in utility functions where setting up closures or classes feels overkill.
function myFunc() {
myFunc.counter = (myFunc.counter || 0) + 1;
return myFunc.counter;
}
Since functions in JS are objects, you can treat them like containers too. This pattern gives you that javascript static variables feel, with even less overhead. It’s a great mix of readability and control—especially in simpler scripts or utilities