A method is a function that belongs to an object. It lets an object do things with its own data.
const user = {
name: "Maya",
greet() {
return "Hello, I am " + this.name;
}
};
console.log(user.greet()); // → Hello, I am Maya
greet() { ... } is shorthand for greet: function () { ... }. Inside a method, this refers to the object the method was called on, which is how it reaches name. See this in JavaScript for the full story.
A more useful example
const cart = {
items: [],
add(name, price) {
this.items.push({ name, price });
},
total() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
};
cart.add("Book", 12);
cart.add("Pen", 3);
console.log(cart.total()); // → 15
console.log(cart.items.length); // → 2
The object keeps its data (items) and the functions that work on it (add, total) together.
Chaining methods
If a method returns this, calls can be chained.
const counter = {
value: 0,
increment() { this.value++; return this; },
double() { this.value *= 2; return this; }
};
console.log(counter.increment().increment().double().value); // → 4
Avoid arrow functions as methods
An arrow function takes this from the surrounding code, not from the object, so it cannot reach the object’s data.
const user = {
userName: "Maya",
regular() { return this.userName; },
arrow: () => this.userName
};
console.log(user.regular()); // → Maya
console.log(user.arrow()); // → undefined
In the arrow function, this is not user. It is whatever this is where the object was written (in a browser script, the window object), so the property is not found. For methods, use the shorthand syntax. Use arrow functions for callbacks inside methods.
Methods on built-in values
Strings, numbers and arrays have methods too: "abc".toUpperCase(), [1, 2].map(...), (5).toFixed(2). JavaScript wraps primitives in temporary objects so they can have methods.
Functions are values
user.greet around, and why it can lose its this when you do.