
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:-
Public Properties
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 directlyUse case: When you donβt mind other code freely accessing or modifying the property.
Private Properties
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 classUse case: When you want to protect internal details (e.g., passwords, IDs, tokens) and prevent outside code from messing with them.