agyanadda@gmail.com

JS Classes

Modern JS and Best Practices 1 min read Updated Dec 1, 2026 Topic 36 of 38

A class is a blueprint for creating many similar objects.

class Student {
  constructor(name, marks) {
    this.name = name;
    this.marks = marks;
  }
  result() {
    return this.marks >= 33 ? 'Pass' : 'Fail';
  }
}

const s1 = new Student('Asha', 82);
s1.result(); // 'Pass'

Key words

  • constructor runs when you create an object with new
  • Methods are written without the function keyword
  • this refers to the current object

Inheritance

class Topper extends Student {
  constructor(name, marks, rank) {
    super(name, marks); // call the parent constructor
    this.rank = rank;
  }
}

Example

Example — Bank account class HTML
<pre id="out"></pre>

<script>
  class Account {
    constructor(owner, balance = 0) {
      this.owner = owner;
      this.balance = balance;
    }
    deposit(amount) { this.balance += amount; return this; }
    withdraw(amount) {
      if (amount > this.balance) throw new Error('Insufficient balance');
      this.balance -= amount;
      return this;
    }
    toString() { return `${this.owner}: ₹${this.balance}`; }
  }

  class Savings extends Account {
    constructor(owner, balance, rate) {
      super(owner, balance);
      this.rate = rate;
    }
    addInterest() { return this.deposit(this.balance * this.rate / 100); }
  }

  const acc = new Savings('Ravi', 1000, 5);
  acc.deposit(500).addInterest();
  let text = acc.toString();
  try { acc.withdraw(99999); } catch (e) { text += '\n' + e.message; }
  document.getElementById('out').textContent = text;
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which keyword creates an object from a class?

Exercise 2 Fill in the Blank

A child class calls its parent constructor with ___().

Exercise 3 True / False

The constructor method runs automatically when an object is created.

Frequently Asked Questions

They look similar, but underneath JavaScript uses prototypes. Classes are a cleaner way to write the same thing.