Lesson 1 of 6 · 10 min · 2 hands-on steps

Classes & Objects in JavaScript

Model real things with classes, the backbone of most large codebases.

Why classes?

As programs grow, you'll have many things that share the same shape and behavior: users, products, carts, orders. A class is a blueprint for them. Each object made from it (an instance) has its own data.

JavaScript · try it
class Player {
  constructor(name) {
    this.name = name;
    this.score = 0;
  }

  addPoints(n) {
    this.score += n;
  }

  describe() {
    return `${this.name} has ${this.score} points`;
  }
}

const ada = new Player("Ada");
const bo = new Player("Bo");
ada.addPoints(10);
console.log(ada.describe());
console.log(bo.describe()); // Bo's score is separate
  • constructor runs once, when you write new Player(...)
  • this means "the object this method was called on"
  • Methods are functions that belong to the object

Classes vs plain objects

For a single config object, a plain { } is fine. Use a class when you'll create many objects with the same behavior, or when the data and the code that changes it belong together.

Static methods

Some functions belong to the class, not to any one object:

JavaScript · try it
class Temperature {
  constructor(celsius) {
    this.celsius = celsius;
  }
  static fromFahrenheit(f) {
    return new Temperature(((f - 32) * 5) / 9);
  }
}

console.log(Temperature.fromFahrenheit(212).celsius);

You've seen Python classes already. JavaScript's work the same way with different syntax: constructor instead of __init__, and this instead of self.

🧪 Practice: 2 steps

0 / 2 done

Step 1 of 2 · A shopping cart

Complete the Cart class:

  • add(name, price) adds an item { name, price } to this.items
  • total() returns the sum of all prices
  • count() returns how many items are in the cart
JavaScript
class Cart {
  constructor() {
    this.items = [];
  }

  add(name, price) {
  }

  total() {
  }

  count() {
  }
}

Output appears here. Press Run or Ctrl/⌘ + Enter.

✅ Check your understanding

  1. What does the constructor do?

  2. Inside a method, what does this refer to?

Create a free account to track your progress.