AtomLearnAtomLearn
DashboardGoalsPathAchievementsReviewSign In
JavaScript CoreNot Started

Classes

ES6 class syntax — constructor, methods, inheritance, static

0%
Knowledge0%
Learn & Drill
Fluency0%
Drill & Speed
Retention0%
Mastery & Review
Confidence0%
All modes
Practice

Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.

Upgrade
Knowledge
Fluency
Retention

Knowledge Debt detected

You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.

Explanation

ES6 es provide a clean syntax for creating objects with shared behavior ( under the hood).

javascript
class Animal {
  constructor(name, sound) {
    this.name  = name;
    this.sound = sound;
  }

  speak() {
    return `${this.name} says ${this.sound}`;
  }

  static create(name, sound) {
    return new Animal(name, sound);
  }
}

const dog = new Animal('Dog', 'woof');
dog.speak();  // 'Dog says woof'

Inheritance with extends:

javascript class Dog extends Animal { constructor(name) { super(name, 'woof'); // call parent constructor this.tricks = []; } learn(trick) { this.tricks.push(trick); } }

Private fields (ES2022):

javascript class BankAccount { #balance = 0; // private — only accessible inside the class deposit(amount) { this.#balance += amount; } get balance() { return this.#balance; } }

Getters and setters:

javascript class Circle { constructor(radius) { this.radius = radius; } get area() { return Math.PI * this.radius ** 2; } set diameter(d) { this.radius = d / 2; } }

Examples

Class hierarchy

Each subclass overrides area() — polymorphism via prototype chain

class Shape {
  area() { return 0; }
  toString() { return `Area: ${this.area()}`; }
}

class Rectangle extends Shape {
  constructor(w, h) { super(); this.w = w; this.h = h; }
  area() { return this.w * this.h; }
}

class Circle extends Shape {
  constructor(r) { super(); this.r = r; }
  area() { return Math.PI * this.r ** 2; }
}

[new Rectangle(4, 5), new Circle(3)].forEach(s => console.log(s.toString()));

Static factory methods

Static methods are called on the class itself, not instances

class Color {
  constructor(r, g, b) { this.r = r; this.g = g; this.b = b; }

  static fromHex(hex) {
    const n = parseInt(hex.replace('#', ''), 16);
    return new Color((n >> 16) & 255, (n >> 8) & 255, n & 255);
  }

  toString() { return `rgb(${this.r}, ${this.g}, ${this.b})`; }
}

console.log(Color.fromHex('#ff6600').toString()); // rgb(255, 102, 0)

How well did you understand this?

Next in JavaScript Core

Optional Chaining & Nullish Coalescing

Continue