Tutorials JavaScript ES6 Classes
Ch 40 / 78
Chapter 39 Intermediate 9 min read JavaScript

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.

What you'll learn
Class declaration syntax — class, constructor, methods
Inheritance — extends, super(), and method overriding
Static methods and static properties
Getters and setters with get / set
Private class fields with # (ES2022)
Class vs function constructor — when to use each

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:

class { }
Class Declaration
A blueprint for creating objects. Defines a constructor to initialise state and any number of methods that all instances share. Replaces the old function-constructor pattern.
Use when: you need multiple objects with the same shape and shared behaviour — users, products, UI components.
extends
Inheritance
A child class inherits all methods from a parent class using extends. The child calls super() to invoke the parent's constructor and can override any method.
Use when: modelling "is-a" relationships — Dog extends Animal, AdminUser extends User.
static
Static Members
Methods and properties that belong to the class itself, not to any instance. Called as ClassName.method(). Perfect for utility functions and factory methods.
Use when: creating helpers, factories, or counters that live on the class — not on individual instances.

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:

class Person {
  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
class — keyword to define the blueprint constructor — special method called by new ClassName() this — refers to the instance being created instance methods — defined directly in the class body, no comma needed
Class body — what can go inside
1 constructor() — initialises instance properties via this.x = val
2 Instance methods — shared by all instances, defined on the prototype
3 static methods/props — live on the class, not on instances
4 get / set — computed property accessors with validation
5 #privateField — truly private, inaccessible from outside (ES2022)
Important class rules
! Not hoisted — must define before use (unlike function declarations)
! Always strict mode — class body runs in strict mode automatically
! Must use new — calling a class without new throws a TypeError
! No commas between method definitions — unlike object literals
! constructor is optional — a default empty one is provided if omitted
JavaScript — Basic Class Declaration
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:

extends — inheritance chain
1 Child extends Parent — child inherits all parent methods
2 super() in constructor — must be called before accessing this
3 Override methods — child redefines a method to change behaviour
4 super.method() — call parent's version alongside override
super — critical rules
! super() first — accessing this before super() throws ReferenceError
! Required when the child defines a constructor — optional if not
! super.method() works in any instance method, not just constructor
! Single inheritance only — JS classes can extend one class at a time
JavaScript — extends & super
// ── 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
JavaScript — static methods & properties
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(); // 2

Getters & 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:

get propName()
Called when the property is read. Must return a value. No parameters. Used for computed properties, formatting, or lazy loading.
set propName(val)
Called when the property is written. Receives the new value. Used for validation, transformation, and updating dependent state.
JavaScript — get & set
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:

# private fields
✓ Declared at class top — #name; or #count = 0;
✓ Accessible only inside the class body — this.#name
✓ Static private too — static #count = 0
✓ #in check — #field in obj safely tests existence
Public field declarations
1 Public fields — name = "default"; at top of class
2 Readable anywhere — can be accessed and modified externally
3 No # prefix — declared without hash, no enforcement
4 Common in React — class components use public state
JavaScript — Private (#) & Public Field Declarations
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!
# vs _ Convention
Before #, 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?
No (TDZ applies)
Yes (function declarations)
Strict mode
Automatic
Must opt in
Inheritance syntax extends + super() Prototype chain wiring (verbose)
Private fields
#field (hard private)
Only convention (_field)
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 & Role System
A base User class with AdminUser and GuestUser extending it for role-based access control.
extends
Bank / Wallet
Use private fields to protect balance. Expose deposit/withdraw methods and a read-only balance getter.
class + #
Game Entities
Entity base class with Player, Enemy, Boss extending it — each overriding attack() and takeDamage().
extends
UI Component Model
React class components extend React.Component, inheriting setState, lifecycle hooks, and the render mechanism.
extends
Factory Methods
Static factory methods like User.createAdmin() or Product.fromJSON(data) make intent explicit without requiring multiple constructors.
static
Custom Errors
Extend the built-in Error class to create typed errors: class ValidationError extends Error {} — catchable and distinguishable.
extends Error
⚡
Free Resource
Download our JavaScript Cheat Sheet
Classes, inheritance, static, private fields & OOP patterns — one printable page.
Get Sheet

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.

Live Editor
✎ Editor
👁 Preview

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:

JavaScript — ES6 Class Recipes
// ── 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"
Quick Check
What happens if you forget to call super() in a child class constructor before using this?
Quick Check
How do you call a static method named create on a class called User?
Quick Check
What does the # prefix do to a class field?
Chapter Summary
  • The class keyword is syntactic sugar over prototypes. Classes are not hoisted, always run in strict mode, and must be called with new — calling without it throws a TypeError.
  • The constructor() method initialises instance properties via this.prop = val. It runs once when new ClassName() is called. It is optional — a default is provided if omitted.
  • extends creates a child class that inherits all parent methods. The child's constructor must call super() before any use of this, or a ReferenceError is thrown.
  • static methods and properties belong to the class itself, not instances. They are called as ClassName.method() and are perfect for factory methods, utility helpers, and class-level counters.
  • get and set define 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel