Problem Statement
What are static methods in JavaScript classes?
Explanation
Static methods belong to the class itself, not to instances of the class.
You call static methods directly on the class, not on objects created from the class.
Static methods cannot access instance properties using this, because they are not called on instances.
Static methods are useful for utility functions related to the class.
Common examples include factory methods, helper functions, and utility operations.
They are defined using the static keyword in classes.
Code Solution
SolutionRead Only
class MathUtils {
// Static method
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
// Instance method
calculate(x, y) {
return x + y;
}
}
// Call static method on class
console.log(MathUtils.add(5, 3)); // 8
console.log(MathUtils.multiply(4, 2)); // 8
// Cannot call on instance
const math = new MathUtils();
// math.add(5, 3); // TypeError!
// Can call instance method
console.log(math.calculate(5, 3)); // 8
// Factory pattern with static method
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
static create(name, email) {
// Validation or processing
if (!email.includes('@')) {
throw new Error('Invalid email');
}
return new User(name, email);
}
static fromJSON(json) {
const data = JSON.parse(json);
return new User(data.name, data.email);
}
}
const user1 = User.create('John', 'john@example.com');
const user2 = User.fromJSON('{"name":"Jane","email":"jane@example.com"}');
// Built-in static methods
console.log(Array.isArray([1, 2, 3])); // true (Array.isArray)
console.log(Object.keys({a: 1})); // ['a'] (Object.keys)
// Static properties (ES2022)
class Config {
static apiUrl = 'https://api.example.com';
static timeout = 5000;
}
console.log(Config.apiUrl); // 'https://api.example.com'
// Inheritance and static methods
class Animal {
static type() {
return 'Animal';
}
}
class Dog extends Animal {
static type() {
return 'Dog';
}
}
console.log(Animal.type()); // 'Animal'
console.log(Dog.type()); // 'Dog'