Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 39 of 58

Classes

Learn how to write JavaScript classes with constructors, methods, getters, static members and private fields, and when a class is worth using.

14 minClasses and errorsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonWrite a class with a constructor, methods, a getter, a static member and a private field, then create objects from it with new.

After this lesson you can describe a kind of thing once, as a class, and then create as many objects of that kind as you like. You will write constructors, methods, getters, static members and private fields, and you will know why this sometimes goes missing.

You already know plain objects from Objects and methods from Methods and this. A class is a tidy way to stamp out many objects that share the same shape and behaviour.

Why classes exist

Imagine a shop with fifty customers. Writing fifty object literals by hand, each with its own copy of the same logic, is tiring and error prone. A class lets you write the shape and the behaviour once.

javascript
class Customer {
  constructor(name, city) {
    this.name = name;
    this.city = city;
  }

  greet() {
    return `Hello, ${this.name} from ${this.city}`;
  }
}

const first = new Customer("Asha", "Pune");
console.log(first.greet()); // Hello, Asha from Pune

Read it in three pieces. The word class followed by a name (capitalised by convention) starts the blueprint. The constructor is a special method that runs when you write new Customer(...); inside it, this is the brand new object, so this.name = name stores a property on it. The greet method has no function keyword and no commas between members.

When you write new Customer("Asha", "Pune"), JavaScript creates an empty object, runs the constructor with this pointing at it, and hands the object back. Every object made this way shares the same greet method instead of getting its own copy.

A first class you can run

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  class Rectangle {
    constructor(width, height) {
      this.width = width;
      this.height = height;
    }
    area() {
      return this.width * this.height;
    }
  }

  const small = new Rectangle(2, 3);
  const big = new Rectangle(10, 20);
  log("small area:", small.area());
  log("big area:", big.area());
  log("same method shared:", small.area === big.area);
</script>
result
small area: 6
big area: 200
same method shared: true

The last line shows that both rectangles use one shared area function. Change the numbers in the editor and watch the result update.

The small log helper at the top writes into the page, because the editor preview has no visible console. We use it in many lessons from here on.

Getters, static members and private fields

Here is a bigger class that uses the other class features. It runs in Node and in the browser.

javascript
class BankAccount {
  #balance = 0;          // private field
  static count = 0;      // belongs to the class

  constructor(owner, opening = 0) {
    this.owner = owner;
    this.#balance = opening;
    BankAccount.count++;
  }

  deposit(amount) {
    if (amount <= 0) throw new Error("Deposit must be positive");
    this.#balance += amount;
    return this;          // lets calls chain
  }

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

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

  static compare(a, b) {  // a static method
    return a.balance - b.balance;
  }
}

const a = new BankAccount("Asha", 100);
a.deposit(50).deposit(25);
console.log(a.describe());        // Asha has 175
console.log(a.balance);           // 175
console.log(BankAccount.count);   // 1
const b = new BankAccount("Ravi");
console.log(BankAccount.compare(a, b)); // 175

Going through the new pieces:

  • Private field. #balance can only be read or written by code inside the class body. Outside, a.#balance is a syntax error, so nobody can set a negative balance behind your back. The only way in is through your methods, which can check the input.
  • Getter. get balance() lets you write a.balance without parentheses. There is no setter here, so assigning a.balance = 5 does nothing in ordinary scripts and throws a TypeError in strict mode or inside modules. The balance stays 175 either way.
  • Static. static count and static compare belong to the class itself. You reach them as BankAccount.count, never through an instance. They suit counters and helper functions that do not need a particular object.
  • Returning this. deposit returns this so you can chain calls, as in a.deposit(50).deposit(25).

A class is still a function underneath

typeof BankAccount is "function". Classes are mostly a cleaner way to write the older constructor-function pattern, and the methods really do live on a shared prototype object. The Prototypes lesson shows what that means. Two practical results follow:

  • A class must be called with new. BankAccount("x") throws TypeError: Class constructor BankAccount cannot be invoked without 'new'.
  • a instanceof BankAccount is true, which is handy for checking what kind of object you were given.

Also notice that Object.keys(a) only lists owner. Methods live on the prototype, the getter likewise, and private fields are hidden, so only own public properties show up.

When this goes missing

Methods rely on this being the object they were called on. Pull a method out of its object and that link breaks.

javascript
class Counter {
  count = 0;
  inc() { this.count++; }
}
const c = new Counter();
const f = c.inc;
f(); // TypeError: Cannot read properties of undefined (reading 'count')

Calling f() has no object in front of the dot, so this is undefined inside class code. This bites hardest when you pass a method as a callback, for example to an event listener. Two fixes work. You can bind it, c.inc.bind(c), or you can define the method as an arrow-function field:

javascript
class Counter2 {
  count = 0;
  inc = () => { this.count++; };
}
const c2 = new Counter2();
const g = c2.inc;
g(); g();
console.log(c2.count); // 2

The arrow function captures this from the moment the object is created. The cost is that each object gets its own copy of inc, so use this form only where you need it.

Should you use classes?

Not always. A plain object and a few functions are often simpler. Classes earn their place when you create many objects of one kind, each with its own data and behaviour, or when you want to enforce rules with private fields. Many working JavaScript programmers use classes lightly and rely on functions and objects for most things.

Common mistakes

  • Forgetting new. The error message is clear once you know it. Always write new ClassName(...).
  • Forgetting this. inside the constructor. Writing name = name; assigns the parameter to itself and the object ends up with nothing. You need this.name = name;.
  • Putting commas between methods. Object literals use commas, class bodies do not. A comma in a class body is a syntax error.
  • Using this before super() in a subclass. You will meet this in Inheritance with extends.
  • Passing a method as a callback and losing this. Bind it or use an arrow-function field.
  • Expecting private fields to be hidden for security. They stop accidental use inside your own program. They do not protect anything from a person who can run code on the page.

Exercise

Write a class Temperature whose constructor takes a value in Celsius. Add a getter fahrenheit that returns the converted value (multiply by 9, divide by 5, add 32) and a static method fromFahrenheit(f) that returns a new Temperature. Create one from 100 Celsius and print its Fahrenheit value (it should be 212), then create one with Temperature.fromFahrenheit(32) and check its Celsius value is 0.

Next, learn how one class can build on another in Inheritance with extends.

Key points

  • A class is a blueprint; new ClassName(...) runs the constructor and returns a fresh object.
  • Methods written in the class body are shared by every object made from it.
  • A getter reads like a property but runs code, and a field starting with
  • static members belong to the class itself, not to the objects it creates.
  • A method that loses its object (const f = obj.method) loses this as well.

Check yourself

1. What happens if you call a class without new, for example Account("Asha")?
2. Where do you write the code that sets up each new object's starting properties?
3. What does a field written as #balance mean?
4. How do you call a static method called compare on the class Account?

Free tools for this lesson