Introduced in ECMAScript 2015 (ES6), Classes bring a clean, formal syntax to Object-Oriented Programming (OOP) in JavaScript. They cleanly encapsulate properties, methods, inheritance (extends), parent calls (super), and private state (#).
class User {
// 1. Constructor Method (Runs upon instantiation with 'new')
constructor(username, email) {
this.username = username;
this.email = email;
}
// 2. Instance Method (Stored on User.prototype)
displayInfo() {
return `User: ${this.username} (${this.email})`;
}
// 3. Static Method (Called directly on Class, not on instances!)
static compareUsers(u1, u2) {
return u1.username === u2.username;
}
}
const user1 = new User("vikram", "v@v.com");
console.log(user1.displayInfo()); // "User: vikram (v@v.com)"
console.log(User.compareUsers(user1, user1)); // true
extends & super()// Parent Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I am ${this.name}`;
}
}
// Child Class extending Person
class Student extends Person {
constructor(name, age, rollNo, semester) {
// super() invokes parent constructor; mandatory before accessing 'this'!
super(name, age);
this.rollNo = rollNo;
this.semester = semester;
}
// Method Overriding
greet() {
return `${super.greet()}, studying in Semester ${this.semester}.`;
}
}
const bcaStudent = new Student("Pooja", 20, 108, 4);
console.log(bcaStudent.greet()); // "Hello, I am Pooja, studying in Semester 4."
#)Introduced in ES2022, private fields provide true language-level encapsulation:
class BankAccount {
// Private field declaration
#balance = 0;
constructor(initialDeposit) {
this.#balance = initialDeposit;
}
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
// Getter Method
get balance() {
return this.#balance;
}
}
const myAccount = new BankAccount(10000);
myAccount.deposit(2500);
console.log("Verified Balance:", myAccount.balance); // 12500
// Direct access throws SyntaxError!
// console.log(myAccount.#balance); // SyntaxError: Private field '#balance' must be declared!
Exam Question: "What are the 4 fundamental pillars of OOP in JavaScript?"
#).extends and super.How does JavaScript coordinate synchronous code, Promises, and timers without blocking? Proceed to: JavaScript Event Loop: Concurrency & Microtasks →
Accelerate your JavaScript mastery by studying these tightly connected core tutorials:
Underlying prototype mechanism of classes.
Instance references in constructor and methods.
Exporting and importing class definitions.
Instance properties and memory layout.