What is a class in JavaScript?
A class in JavaScript is a syntactic way to describe objects and their behavior (methods), introduced in the ES6 (ECMAScript 2015) standard. It is syntactic sugar over the prototypal inheritance that already existed in the language. In other words, under the hood classes work through the same prototype mechanisms.
Key Features of a Class
- Declaring a class:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hi, my name is ${this.name}`);
}
}
const user = new Person("Alice", 25);
user.greet(); // Hi, my name is Alice- The
constructor()method is called when a new instance is created (new Person()). thisinside the constructor refers to the object being created.
Class Inheritance
Classes can inherit properties and methods from other classes using the extends keyword.
class Animal {
speak() {
console.log("The animal makes a sound");
}
}
class Dog extends Animal {
speak() {
console.log("The dog barks");
}
}
const dog = new Dog();
dog.speak(); // The dog barksIf you need to call the parent's method, use super():
class Dog extends Animal {
speak() {
super.speak(); // calls the parent's method
console.log("Woof woof");
}
}Static Methods and Properties
Sometimes a method belongs not to a specific instance, but to the class itself:
class MathUtils {
static square(n) {
return n * n;
}
}
console.log(MathUtils.square(5)); // 25Static methods cannot be called on an instance (
new MathUtils()), only on the class itself.
Getters and Setters
Let you control access to a class's properties:
class User {
constructor(name) {
this._name = name;
}
get name() {
return this._name.toUpperCase();
}
set name(value) {
this._name = value.trim();
}
}
const u = new User(" Alice ");
console.log(u.name); // ALICEPrivate Fields and Methods
The # syntax makes a property or method inaccessible from outside:
class Account {
#balance = 0;
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const acc = new Account();
acc.deposit(100);
console.log(acc.getBalance()); // 100
// acc.#balance - Error: private propertySummary
| Feature | Description |
|---|---|
constructor() | Initializes the instance |
extends | Inheritance |
super | Calls the parent's constructor or method |
static | Methods on the class, not the instance |
get / set | Controls access to properties |
# | Private fields and methods |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.