class, constructor & methods

Classes

Lesson 9 of 20 · 11 min · Module 3: Classes and objects

When several objects share the same shape and behaviour, a class describes them once. Each object created from it, called an instance, gets its own data and shares the methods.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Define a class with a constructor and methods
  • Create instances with new
  • Protect an object’s rules inside its methods

The idea

A class has a constructor that sets up a new instance with this, and methods that work with that data. Create instances with new. Throwing an error from a method stops invalid operations before they change anything.

class Course {
  constructor(title, lessons) {
    this.title = title;
    this.lessons = lessons;
  }
  describe() {
    return this.title + " (" + this.lessons + " lessons)";
  }
}
console.log(new Course("JavaScript", 20).describe());

01One description, many objects

The class is a blueprint. new BankAccount("Ana") runs the constructor with this pointing at a brand-new object, which is then returned.

02Methods are shared

deposit lives once on BankAccount.prototype and every instance uses it. Data such as balance and history belongs to each instance, which is why it is set in the constructor.

class Dog {
  bark() { return "woof"; }
}
const a = new Dog(), b = new Dog();
console.log(a.bark === b.bark);
Output
true

03Check before you change

Validating the amount and the balance before touching anything means a failed withdraw never leaves a half-updated account behind.

Your turn

Write a class BankAccount. new BankAccount("Ana", 100) stores owner and balance (default 0) and an empty history array. deposit(amount) and withdraw(amount) change the balance, push { type: "deposit" | "withdraw", amount } to history and return the new balance. Both throw a RangeError for amounts that are not positive numbers, and withdraw also throws one when the balance is too low, without changing anything.

What the checks look for

  • Creates accounts with an owner, a balance and a history
  • Deposits and withdrawals update the balance and history
  • Rejects invalid amounts
  • Refuses to overdraw and leaves the account unchanged
  • Each account has its own history
Try it in the editor →

Take this with you

A class keeps data and the rules for changing it together.

Go a little further

Add transfer(to, amount) that withdraws from one account and deposits into another, failing safely if either step is invalid.

Learn JavaScript Intermediate for free

20 short lessons with real code and instant checks.

See the whole course →