Class (JavaScript)

A class in JavaScript is a blueprint for creating objects, defined with the class keyword.

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

Defining a Class#

class Player {
}

By convention, class names use PascalCase: Player, OddsAndEvens, RockPaperScissors.

Adding a Constructor#

The constructor method runs automatically when an object is created. Use it to set the initial state.

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

this.name = name stores the value on the object. this refers to the current instance.

Adding a Method#

Methods in a JavaScript class are defined without the function keyword — just the name and parentheses.

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

    greet() {
        console.log(`Hello, I am ${this.name}!`);
    }
}

Creating an Object#

Use new followed by the class name and any constructor arguments.

const player = new Player("Alice");
player.greet();

Common Mistakes#

Forgetting this when accessing object data Inside a method, name and this.name are different things. name looks for a local variable. this.name accesses the property on the object. Always use this to refer to the object’s own data.

Forgetting new when creating an object Calling Player("Alice") without new doesn’t create an object — it runs the constructor as a plain function and returns undefined. Always use new.

Using function inside a class Methods inside a class body don’t use the function keyword. Writing function greet() {} inside a class is a syntax error. Just write greet() {}.

Confusing class syntax with object literal syntax An object literal uses key: value pairs with commas: { name: "Alice" }. A class uses method definitions without commas. Mixing the two syntaxes is a common early mistake.

Resources#