Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 156 ยท Classes and Objects in Depth

Classes

Learn JavaScript class syntax - write a constructor, add methods, fields, getters and setters, create instances with new, and avoid pitfalls with this.

When your program needs many objects of the same kind (bank accounts, shopping carts, game characters, timers), you want one blueprint that describes what each object holds and what it can do. In JavaScript, that blueprint is a class.

You saw in Prototypes that JavaScript already shares methods between objects through the prototype chain. A class is a clear, compact syntax for setting that up. It gives you a constructor, methods, fields, getters and setters in one readable block. This lesson covers all of them, plus the mistakes that trip up almost everyone at first.

Your first class

A class declaration starts with class, a name in PascalCase, and a body in braces. Inside, the special constructor method runs every time you create a new object, and the other methods describe its behavior:

JS A first class

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each object made from a class is called an instance. new Timer("Tea", 3) does four things:

  1. Creates a new, empty object.
  2. Links it to Timer.prototype, where tick and describe live.
  3. Runs constructor with this set to the new object, so this.label = label creates its properties.
  4. Returns the finished object.

Notice there are no commas between methods in a class body, unlike in an object literal. And this inside a method refers to the instance the method was called on: tea.tick() changes tea, never eggs.

What a class really is

A class is a special kind of function, and its methods live on its prototype, exactly like the constructor functions from the previous lesson:

JS Under the hood

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Classes add a few safety features that old constructor functions lacked:

  • Calling a class without new throws a TypeError instead of silently misbehaving.
  • Class bodies always run in strict mode.
  • Methods are non-enumerable, so they don't show up in for...in loops.
  • Class declarations are not usable before the line that defines them. Like let and const, they sit in the temporal dead zone until then (see Scope and Hoisting).

The constructor

The constructor sets up a new instance. It is the place to check arguments and give every property a starting value:

JavaScript
class Temperature {
  constructor(celsius) {
    if (typeof celsius !== "number" || Number.isNaN(celsius)) {
      throw new TypeError("celsius must be a number");
    }
    this.celsius = celsius;
  }
}

A few rules:

  • A class can have at most one constructor. JavaScript has no overloading; use default and rest parameters or an options object instead.
  • If you leave the constructor out, JavaScript supplies an empty one.
  • Don't return anything from a constructor. The new instance is returned automatically.

For more than two or three arguments, take a single object and destructure it. Callers can then pass options in any order and skip the ones with defaults:

JavaScript
class Toast {
  constructor({ message, type = "info", duration = 3000 }) {
    this.message = message;
    this.type = type;
    this.duration = duration;
  }
}

new Toast({ message: "Saved!", duration: 1500 });

Class fields

Assigning every property in the constructor works, but it hides the shape of your objects inside a function. Class fields let you declare instance properties directly in the class body, with an optional starting value:

JS Class fields and method chaining

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Field initializers run once per instance, just before the constructor body. That is why each cart gets its own items array. (Compare that with a value put on the prototype, which would be shared by every instance.) Fields are supported in all modern browsers and Node.js 12+.

Getters and setters

A class can define getters and setters with get and set. From the outside they look like plain properties, but they run code when read or assigned. Getters are perfect for values computed from other data; setters are perfect for validation:

JS Getters and setters in a class

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The underscore in _celsius is only a convention meaning "please don't touch this". Code outside the class can still read and change it. In Private Fields and Static Members you will replace it with a truly private #celsius field.

Losing this

Methods are just functions stored on the prototype. If you take a method off its object and call it on its own, the link to the instance is lost, and because class bodies are strict, this becomes undefined:

JavaScript
const tea = new Timer("Tea", 3);
const tick = tea.tick;
tick(); // TypeError: Cannot read properties of undefined (reading 'remaining')

This happens most often with callbacks: setTimeout(tea.tick, 1000) or button.addEventListener("click", cart.clear). There are three common fixes:

JavaScript
setTimeout(() => tea.tick(), 1000);   // 1. wrap the call in an arrow function
setTimeout(tea.tick.bind(tea), 1000); // 2. bind this (see the bind lesson)

class Timer {
  tick = () => {                      // 3. an arrow function stored as a field
    if (this.remaining > 0) this.remaining--;
  };
}

Option 3 works because an arrow function takes this from where it was created, and a field initializer runs with this set to the new instance. The trade-off: every instance gets its own copy of the function instead of sharing one on the prototype. Use it for methods you know will be passed around as callbacks. The this keyword and call, apply and bind lessons go deeper.

Class expressions and other details

Like functions, classes can also be written as expressions and stored in variables, passed to functions or returned from them:

JavaScript
const Greeter = class {
  greet(name) { return `Hello, ${name}!`; }
};

Two more useful features fit naturally into a class body:

  • Computed method names, such as [Symbol.iterator]() { ... }, which makes instances work with for...of and spread. You will build one in Iterators and Generators.
  • A toString() method, which controls how an instance looks when it is turned into a string, for example in a template literal.

When to use a class

Classes are a good fit when you have many objects with the same shape and behavior and those objects keep state that changes over time: a cart, a game entity, a connection, a UI widget. They also help when you need inheritance or private state.

For one-off objects, an object literal is simpler. For pure calculations with no state, a plain function is simpler. JavaScript lets you mix all three styles, and the final lesson of this chapter, Composition over Inheritance, looks at how to choose.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does a method defined in a class body, like tick() { ... }, end up?

    Class methods are placed on ClassName.prototype, so all instances share one copy and find it through the prototype chain.
  2. 2. What happens if you call a class like a normal function, without new?

    Classes can only be called with new. Calling one directly throws a TypeError, which protects you from a classic constructor-function bug.
  3. 3. Given class Bag { items = []; }, what is true about two instances a and b?

    Field initializers run once for every new instance, so each instance gets a fresh array as an own property.
  4. 4. const f = timer.tick; f(); throws because this is undefined. Which fix keeps this pointing at timer?

    The arrow function calls tick as a method of timer, so this is set correctly. timer.tick.bind(timer) would work too.
  5. 5. Why use a getter like get fahrenheit() instead of storing a fahrenheit property?

    A getter calculates its value when read, so fahrenheit always matches the current celsius.

Summary

  • A class is a blueprint; new ClassName(...) creates an instance and runs its constructor.
  • Methods go on the class's prototype and are shared; each instance holds its own data.
  • Class fields (items = []) declare instance properties with starting values, created fresh for every instance.
  • get and set define computed and validated properties.
  • Classes must be called with new, run in strict mode and can't be used before their declaration.
  • Detached methods lose this: wrap them in an arrow function, bind them, or define them as arrow-function fields.

Next: Inheritance with extends and super โ€” building specialized classes on top of existing ones.