ES6 Classes
Introduced in ES6 (2015), the
class keyword brings a clean,
familiar syntax for creating objects and implementing
inheritance in JavaScript. Classes are
syntactic sugar over prototypes — they don't add new behaviour,
but dramatically improve readability. You'll learn the full anatomy:
constructor, instance methods,
extends, super,
static members,
getters & setters, and private fields — everything used in
modern JavaScript and React every day.
Three Core Class Concepts
ES6 classes bring three core OOP concepts to JavaScript with clean, readable syntax. Understanding each concept independently — before combining them — is the fastest way to master classes:
constructor
to initialise state and any number of methods that all instances share. Replaces the old
function-constructor pattern.extends. The child calls super() to invoke the parent's
constructor and can override any method.
ClassName.method(). Perfect for utility
functions and factory methods.Class Syntax & Anatomy
Every class follows a predictable structure. Learn the anatomy once and you'll instantly read any JavaScript class — whether written by you or a third-party library:
constructor(name, age) { // ← runs when new Person() is called
this.name = name;
this.age = age;
}
greet() { // ← instance method
return `Hi, I'm ${this.name}`;
}
}
const p = new Person("Alice", 28); // create instance
this.x = val
new throws a TypeError
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hi, I'm ${this.name} and I'm ${this.age} years old.`;
}
haveBirthday() {
this.age++;
return `Happy birthday, ${this.name}! Now ${this.age}.`;
}
}
const alice = new Person("Alice", 28);
const bob = new Person("Bob", 32);
alice.greet(); // "Hi, I'm Alice and I'm 28 years old."
bob.greet(); // "Hi, I'm Bob and I'm 32 years old."
alice.haveBirthday(); // "Happy birthday, Alice! Now 29."
// ── instanceof check ─────────────────────────────────────────
alice instanceof Person; // true
// ── Class expression (alternative syntax) ────────────────────
const Animal = class {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound.`; }
};Inheritance — extends & super
The extends keyword lets a
child class inherit all methods from a parent. The child uses
super() to call the parent's constructor
and super.method() to call parent methods
from within an override:
this
this
before super() throws ReferenceError
// ── Parent class ──────────────────────────────────────────────
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
describe() {
return `I am ${this.name}.`;
}
}
// ── Child class — inherits from Animal ────────────────────────
class Dog extends Animal {
constructor(name, breed) {
super(name); // ✓ must call super() before this
this.breed = breed;
}
speak() { // ← override parent method
return `${this.name} barks! 🐕`;
}
fullInfo() {
return `${super.describe()} I'm a ${this.breed}.`; // super.method()
}
}
class Cat extends Animal {
speak() { return `${this.name} meows! 🐈`; }
}
const dog = new Dog("Rex", "Labrador");
const cat = new Cat("Whiskers");
dog.speak(); // "Rex barks! 🐕" (overridden)
cat.speak(); // "Whiskers meows! 🐈" (overridden)
dog.describe(); // "I am Rex." (inherited from Animal)
dog.fullInfo(); // "I am Rex. I'm a Labrador."
dog instanceof Dog; // true
dog instanceof Animal; // true — instance of parent too!
Static Methods & Properties
static members belong to
the class itself, not to any instance. You call them
as ClassName.method() — not
instance.method(). They're perfect for
factory methods, utility helpers, and class-level counters:
| Feature | Instance member | Static member |
|---|---|---|
| Belongs to | Each object instance | The class itself |
| Called via | instance.method() |
ClassName.method() |
| Access to this | Yes — refers to instance | Yes — refers to the class |
| Shared between instances | Method shared, state separate | Fully shared |
| Common use | greet(), getTotal(), validate() | factory(), count, utils |
class MathUtils {
static add(a, b) { return a + b; }
static multiply(a, b) { return a * b; }
static clamp(n, lo, hi){ return Math.min(Math.max(n, lo), hi); }
}
MathUtils.add(3, 4); // 7 — called on class, not instance
MathUtils.clamp(15, 0, 10); // 10
// ── Static factory method pattern ────────────────────────────
class User {
static #count = 0; // static private field
constructor(name, role) {
this.name = name;
this.role = role;
User.#count++;
}
static createAdmin(name) {
return new User(name, "admin"); // factory
}
static createGuest() {
return new User("Guest", "guest");
}
static getCount() { return User.#count; }
}
const admin = User.createAdmin("Alice");
const guest = User.createGuest();
User.getCount(); // 2Getters & Setters
Getters and setters let you define computed properties and add validation logic when reading or writing a value. They look like properties at the call site but execute code behind the scenes — keeping the public API clean while protecting internal state:
class Temperature {
constructor(celsius) {
this._celsius = celsius; // _ prefix = convention for "internal"
}
get fahrenheit() { return this._celsius * 9/5 + 32; }
get celsius() { return this._celsius; }
set celsius(val) {
if (val < -273.15) throw new RangeError("Below absolute zero!");
this._celsius = val;
}
}
const temp = new Temperature(100);
temp.fahrenheit; // 212 — reads like a property, not a method call
temp.celsius; // 100
temp.celsius = 37; // setter validates and stores
temp.fahrenheit; // 98.6
// ── Getter for full name ──────────────────────────────────────
class Person {
constructor(first, last) {
this.first = first;
this.last = last;
}
get fullName() { return `${this.first} ${this.last}`; }
set fullName(val) {
[this.first, this.last] = val.split(" ");
}
}
const p = new Person("Alice", "Smith");
p.fullName; // "Alice Smith"
p.fullName = "Bob Jones"; // splits and sets first/last
p.first; // "Bob"Private Class Fields #
ES2022 introduced true private fields using the
# prefix. Private fields are
hard-private — they are completely inaccessible outside the class body,
even from subclasses. This is unlike the old
_prefix convention which was just a gentleman's
agreement and not enforced by the language:
#name;
or #count = 0;
this.#name
static #count = 0
#field in obj
safely tests existence
name = "default"; at top of class
class BankAccount {
#balance = 0; // private field — inaccessible from outside
#owner; // private — declared, assigned in constructor
currency = "INR"; // public field — readable and settable externally
constructor(owner, initial = 0) {
this.#owner = owner;
this.#balance = initial;
}
deposit(amount) {
if (amount <= 0) throw Error("Amount must be positive");
this.#balance += amount;
return this; // chain
}
withdraw(amount) {
if (amount > this.#balance) throw Error("Insufficient funds");
this.#balance -= amount;
return this;
}
get balance() { return this.#balance; } // expose balance read-only
statement() { return `${this.#owner}: ${this.currency} ${this.#balance}`; }
}
const acc = new BankAccount("Alice", 1000);
acc.deposit(500).withdraw(200); // chain: balance = 1300
acc.balance; // 1300 — via getter
acc.statement(); // "Alice: INR 1300"
acc.#balance; // ✗ SyntaxError — private field!
#, developers used _balance as a
convention to signal "don't touch this from outside" —
but nothing stopped external code from doing so.
The # prefix is enforced by the JavaScript engine:
accessing a private field from outside the class throws a
SyntaxError at parse time. Use # for
anything you genuinely want encapsulated.
Class vs Constructor Function
ES6 classes are syntactic sugar over JavaScript's existing prototype-based system. The same object structure can be expressed both ways — but classes are dramatically more readable and less error-prone:
| Feature | ES6 Class | Constructor Function |
|---|---|---|
| Syntax | class Person {} | function Person() {} |
| Hoisted? |
|
|
| Strict mode |
|
|
| Inheritance syntax | extends + super() |
Prototype chain wiring (verbose) |
| Private fields |
#field (hard private)
|
|
| Static members | static method() {} |
Manually on the function object |
| Underlying mechanism | Same prototypes | Same prototypes |
Real-World Use Cases
ES6 classes are the building block of modern JavaScript frameworks and business logic. Here are the real scenarios you'll model with them every day:
User class with AdminUser and
GuestUser extending it for role-based access control.
Entity base class with Player,
Enemy, Boss extending it — each overriding
attack() and takeDamage().
React.Component,
inheriting setState, lifecycle hooks, and the render mechanism.User.createAdmin() or
Product.fromJSON(data) make intent explicit without requiring multiple
constructors.
Error class to create typed errors:
class ValidationError extends Error {} — catchable and distinguishable.
Try It — Live Editor
Experiment with ES6 classes below. Try modifying the class hierarchy, adding methods, or testing private fields — all without leaving this page.
Common Patterns & Recipes
These class patterns appear constantly in real JavaScript, React, Node.js and TypeScript codebases. Master them to read and write professional-grade OOP code:
// ── Custom Error classes ──────────────────────────────────────
class AppError extends Error {
constructor(message, statusCode = 500) {
super(message);
this.name = "AppError";
this.statusCode = statusCode;
}
}
class NotFoundError extends AppError {
constructor(resource) {
super(`${resource} not found`, 404);
this.name = "NotFoundError";
}
}
throw new NotFoundError("User"); // NotFoundError: User not found (404)
// ── Mixin pattern ─────────────────────────────────────────────
const Serializable = Base => class extends Base {
toJSON() { return JSON.stringify(this); }
static fromJSON(json) { return Object.assign(new this(), JSON.parse(json)); }
};
class Product extends Serializable(Object) {
constructor(name, price) { super(); this.name = name; this.price = price; }
}
// ── Singleton ─────────────────────────────────────────────────
class Config {
static #instance = null;
static getInstance() {
if (!Config.#instance) Config.#instance = new Config();
return Config.#instance;
}
#settings = { theme: "dark", lang: "en" };
get(key) { return this.#settings[key]; }
set(key, val) { this.#settings[key] = val; }
}
Config.getInstance().get("theme"); // "dark"super() in a child class
constructor before using this?static method named create on a
class called User?# prefix do to a class field?- The
classkeyword is syntactic sugar over prototypes. Classes are not hoisted, always run in strict mode, and must be called withnew— calling without it throws a TypeError. - The
constructor()method initialises instance properties viathis.prop = val. It runs once whennew ClassName()is called. It is optional — a default is provided if omitted. extendscreates a child class that inherits all parent methods. The child's constructor must callsuper()before any use ofthis, or a ReferenceError is thrown.staticmethods and properties belong to the class itself, not instances. They are called asClassName.method()and are perfect for factory methods, utility helpers, and class-level counters.getandsetdefine computed accessors that look like properties but execute code. Getters return computed values; setters add validation before storing data.- The
#prefix (ES2022) creates hard-private fields — inaccessible outside the class body at the syntax level. This enforces encapsulation beyond the old_naming convention. - Common patterns include: custom errors (
class AppError extends Error), factory methods, singleton via a static private instance, and mixins for composing behaviour from multiple sources.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.