CodeMIRAI
0 XP

Classes

2 min read 5 runnable examples Quiz included

A class is a blueprint for creating objects that share structure and behaviour.

JavaScript
class Account {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }

  deposit(amount) {
    this.balance += amount;
    return this;              // returning this allows chaining
  }

  describe() {
    return `${this.owner} has ₹${this.balance}`;
  }
}

const acct = new Account("Asha", 100);
acct.deposit(50).deposit(25);
console.log(acct.describe());
  • constructor runs when you create an object with new.
  • Methods are written without the function keyword.
  • this is the object the method was called on.

Private fields

Fields starting with # can only be used inside the class:

JavaScript
class Wallet {
  #balance = 0;

  add(amount) {
    if (amount <= 0) throw new Error("Amount must be positive");
    this.#balance += amount;
  }

  get balance() {             // a getter: read like a property
    return this.#balance;
  }
}

const w = new Wallet();
w.add(40);
console.log(w.balance);
console.log(w["#balance"]);   // undefined: there's no way in from outside

Getters and setters

JavaScript
class Temperature {
  #celsius = 0;

  get fahrenheit() {
    return this.#celsius * 9 / 5 + 32;
  }

  set celsius(value) {
    if (value < -273.15) throw new Error("Below absolute zero!");
    this.#celsius = value;
  }
}

const t = new Temperature();
t.celsius = 25;
console.log(t.fahrenheit);

Static members

static members belong to the class itself, not to instances:

JavaScript
class MathUtils {
  static PI = 3.14159;
  static circleArea(r) {
    return MathUtils.PI * r * r;
  }
}
console.log(MathUtils.circleArea(2));

Inheritance with extends

JavaScript
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a sound`;
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);                 // call the parent constructor first
    this.breed = breed;
  }
  speak() {
    return `${this.name} the ${this.breed} barks`;
  }
}

const pets = [new Animal("Generic"), new Dog("Rex", "beagle")];
pets.forEach((p) => console.log(p.speak()));
console.log(pets[1] instanceof Animal);
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.