Skip to content
Codewilds

Lesson 25 of 34 · Classes & Errors

JavaScript Classes: Constructors, Getters and Setters

medium20 XP3 min read

In the Objects chapter you built heroes with a factory function that returned an object literal. That works, but when your game needs hundreds of heroes, monsters and items that share the same shape and behaviour, JavaScript offers a dedicated tool: classes.

A class is a blueprint. You describe the data and methods once, then create as many objects (instances) from it as you like.

Defining a class

class Monster {
  constructor(name, hp) {
    this.name = name;
    this.hp = hp;
  }

  roar() {
    return `${this.name} roars!`;
  }
}

const goblin = new Monster("Goblin", 30);
const troll = new Monster("Troll", 120);

console.log(goblin.roar()); // Goblin roars!
console.log(troll.hp);      // 120
console.log(goblin instanceof Monster); // true
  • class Monster { ... } declares the blueprint. Class names are written in PascalCase.
  • The constructor runs automatically when you create an instance with new. Inside it, this is the brand-new object, and you set its properties.
  • Methods are written without the function keyword. They're shared by all instances instead of being copied into each one.

Class fields

Properties that start with the same value for every instance can be declared directly in the class body as fields:

class Chest {
  isOpen = false;
  items = [];

  open() {
    this.isOpen = true;
  }
}

Private fields

Sometimes data should not be changed from outside. Fields whose names start with # are private: they can only be used by code inside the class body.

class Vault {
  #gold = 0;

  deposit(amount) {
    this.#gold += amount;
  }

  balance() {
    return this.#gold;
  }
}

const vault = new Vault();
vault.deposit(50);
console.log(vault.balance()); // 50
console.log(vault.gold);      // undefined: the private field is invisible from outside
// vault.#gold = 1000;        // SyntaxError: private field outside its class

Getters and setters

A getter is a method that is used like a property, so there are no parentheses when you read it. It's great for computed values:

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

  get area() {
    return this.width * this.height;
  }
}

const rect = new Rectangle(3, 4);
console.log(rect.area); // 12 (not rect.area())

A setter runs when you assign to the property, which makes it the perfect place for validation. Getters and setters are often paired with a private field that holds the real value:

class Player {
  #name = "";

  get name() {
    return this.#name;
  }

  set name(value) {
    this.#name = value.trim() || "Anonymous";
  }
}

const p = new Player();
p.name = "   ";
console.log(p.name); // Anonymous

Common mistakes

  • Forgetting new. Monster("Goblin", 30) throws TypeError: Class constructor Monster cannot be invoked without 'new'.
  • Forgetting this. inside methods: hp is a variable, this.hp is the property.
  • A setter that assigns to itself. set name(v) { this.name = v; } calls the setter again and again until the stack overflows. Store the value in a differently named (usually private) field.
  • Calling a getter like a method. rect.area() fails because rect.area is already the number.

Assignment

Complete the Character class:

  • constructor(name, hp) sets name and maxHp, and stores the starting hit points in a private field #hp. hp defaults to 100.
  • A getter hp returns the current hit points.
  • A setter hp stores a new value, but clamps it between 0 and maxHp.
  • A getter isAlive returns true while hp is above 0.
  • takeDamage(amount) lowers hp by amount (never below 0).
  • describe() returns a status line like "Ada (70/100 HP)".
const ada = new Character("Ada");
ada.takeDamage(30);
ada.describe(); // "Ada (70/100 HP)"
ada.hp = 500;
ada.hp;         // 100 (clamped)

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Classes, objects and structs in other languages

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+20 XP

Lesson 25 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.