JavaScript Interview Question #111
What are static methods and static fields in JavaScript classes?
Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate
Quick Interview Answer
Static members belong to the class constructor itself rather than to individual instances. They are useful for utility behavior, factories, counters, configuration, or operations conceptually related to the class but not dependent on a particular instance.
Detailed Explanation
Static members belong to the class constructor itself rather than to individual instances. They are useful for utility behavior, factories, counters, configuration, or operations conceptually related to the class but not dependent on a particular instance.
An instance does not access a static member through this in the same way it accesses an instance method.
Code Example
class MathHelper {
static version = "1.0";
static add(a, b) {
return a + b;
}
}
console.log(MathHelper.version);
console.log(MathHelper.add(2, 3));