Constructor (JavaScript)

In JavaScript, the constructor is a special method inside a class that runs automatically when you create an object with new.

This page covers Constructor in JavaScript. For a language-agnostic introduction, see Constructor.

Defining a Constructor#

The constructor method is always named constructor. It receives arguments and uses this to store them on the object.

class Player {
    constructor(name) {
        this.name = name;
    }
}

Creating an Object#

Pass arguments to new when creating the object. JavaScript calls constructor automatically.

const player = new Player("Alice");
console.log(player.name); // Alice

Default Constructor#

If you don’t define a constructor, JavaScript provides an empty one automatically. Once you define one, yours replaces it entirely.

Default Parameter Values#

Parameters can have default values, making them optional.

class Player {
    constructor(name = "Player") {
        this.name = name;
    }
}

const player = new Player();
console.log(player.name); // Player

Common Mistakes#

Forgetting this when storing values Inside the constructor, name is just a local parameter. this.name is the property on the object. Writing name = name does nothing useful — the value is never attached to the object.

Naming the constructor anything other than constructor The method must be named exactly constructor. Writing init() or setup() creates a regular method that won’t run automatically on object creation.

Forgetting new when creating an object Calling Player("Alice") without new doesn’t create an object — in strict mode it throws a TypeError, in non-strict mode this binds to the global object, causing hard-to-debug behaviour. Always use new.

Trying to return a value Returning a primitive from a constructor is silently ignored. Returning an object replaces the newly created instance — almost never what you want. Don’t return anything from a constructor.

Resources#