Method (JavaScript)

A method in JavaScript is a function defined inside a class body.

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

Defining a Method#

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

class Player {
    greet() {
        console.log("Hello!");
    }
}

By convention, method names use camelCase: greet, play, getScore.

Return Values#

Use return to send a value back. A method without a return statement returns undefined.

class Player {
    add(a, b) {
        return a + b;
    }
}

Accessing Object Data#

Inside a method, use this to access the object’s own properties.

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

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

Calling a Method#

Call a method on an object using dot notation.

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

Common Mistakes#

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

Forgetting this when accessing object data Inside a method, name looks for a local variable. this.name accesses the property on the object. Forgetting this results in a ReferenceError or unexpected undefined value.

Arrow functions losing this If you define a method as an arrow function — greet = () => {}this behaves differently. For regular class methods, use the standard syntax greet() {} to avoid unexpected this binding issues.

Confusing method definition with method call player.greet references the method. player.greet() calls it. Forgetting the parentheses means the method never runs.

Resources#