Stop 07 · Modern JavaScriptTopics · 3/9

Classes

Part of the Web Development Roadmap

In short

When you need many objects of the same shape, like 200 students or 50 products, a class is the blueprint that stamps them out with the same fields and methods.

Classes are a template for creating objects with the same shape and methods, using a constructor to set up each new object.

The jaadu mascot holds a blueprint in front of three identical, differently coloured buildings.

Think of it like this

The builder's flat plan

A housing society has one 2BHK plan: same rooms, same balcony. Every flat built from it has its own owner and its own paint colour. The class is the plan. Each object you make with new is one flat.

Watch it happen

new Topper("Meera", 1)

Your code
Topper
Student

new Topper("Meera", 1)

1/6new creates an empty object and runs Topper's constructor.

The big ideas

What you need to know

constructor sets things up

It runs when you call new Student(...) and sets the starting values on this.

Methods are shared

Methods written in the class live in one place and are shared by every object, so they don't use extra memory per object.

extends and super

class Topper extends Student reuses everything from Student. Call super() in the constructor before using this.

#private and static

#fees can only be read inside the class. static belongs to the class itself, not to each object.

See it in code

Walk through the code

js
1class Student {2  #fees = 0;                       // private field3  static count = 0;4  constructor(name) {5    this.name = name;6    Student.count++;7  }8  pay(amount) { this.#fees += amount; return this.#fees; }9}10 11class Topper extends Student {12  constructor(name, rank) { super(name); this.rank = rank; }13}14 15const t = new Topper("Meera", 1);16console.log(t.pay(500), Student.count);   // 500 1

1/5A private field and a static counter shared by the class.

Topper gets pay() from Student for free. Try t.#fees from outside the class and you'll get a SyntaxError, which is exactly the point.

Save yourself the pain

Common mistakes

Oops

Calling Student("Meera") without new.

Do this instead

Classes throw "Class constructor Student cannot be invoked without 'new'". Always use new Student(...).

Oops

Using this in a child constructor before calling super().

Do this instead

That throws a ReferenceError. Call super(...) first, then set your own fields.

Your mission

Model a library

~25 min

Quick check

What does this log? class A {} console.log(typeof A);

Go deeper

  1. 1Write a BankAccount class with deposit and withdraw methods.
  2. 2Create a SavingsAccount that extends BankAccount and adds interest.
  3. 3Notice that React today mostly uses functions, but classes still appear in many codebases.

Also part of these roadmaps

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge