Static Method in JavaScript
Static methods are defined on the class itself, not on the instances (objects) created from it. They are called using the class name, not this or the object.
Useful for utility/helper functions that donโt depend on individual object data.
Example of Static Method
class Calculator {
// Static method (belongs to the class, not objects)
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
// Normal method (belongs to object)
showMessage() {
console.log("I am an instance method.");
}
}
// Calling static methods
console.log(Calculator.add(5, 10)); // 15
console.log(Calculator.multiply(3, 4)); // 12
// Trying to call static method from object will fail
let calc = new Calculator();
console.log(calc.add); // undefined
// But we can call instance methods from objects
calc.showMessage(); // "I am an instance method."
Explanation:-
static methods are accessed directly using the class name, not through objects.
They are good for utility operations (e.g., math functions, data formatters).
Instances (like calc) cannot call static methods directly.
Public Properties
Definition: Properties that can be accessed directly from outside the class.
Default in JavaScript (everything is public unless explicitly marked private).
Example:-
class Person {
constructor(name) {
this.name = name; // public
}
}
let p = new Person("Alice");
console.log(p.name); // "Alice" (accessible from outside)
p.name = "Bob"; // Can modify directly
Use case: When you donโt mind other code freely accessing or modifying the property.
Private Properties
Definition: Properties that can only be accessed inside the class itself.
Introduced in ES2022 with the # syntax.
Example:-
class Person {
#ssn; // private property
constructor(name, ssn) {
this.name = name; // public
this.#ssn = ssn; // private
}
getSSN() {
return this.#ssn; // accessible inside class
}
}
let p = new Person("Alice", "123-45-6789");
console.log(p.name); // public โ "Alice"
console.log(p.getSSN()); // "123-45-6789"
console.log(p.#ssn); // SyntaxError: Private field '#ssn' must be declared in an enclosing class
Use case: When you want to protect internal details (e.g., passwords, IDs, tokens) and prevent outside code from messing with them.