Object Methods
Functions on objects, the 'this' keyword, and built-in utilities.
Defining Methods
Functions that belong to an object.
const calculator = {
// Method shorthand (preferred):
add(a, b) {
return a + b;
},
// Function expression:
subtract: function(a, b) {
return a - b;
},
// ✗ Arrow (avoid for methods — wrong 'this'):
multiply: (a, b) => a * b,
};
calculator.add(5, 3); // 8
calculator.subtract(10, 4); // 6💡 Use the shorthand syntax — it's concise and properly handles this.
The this Keyword
'this' refers to the object calling the method.
const user = {
name: "Alice",
greet() {
return `Hi, I'm ${this.name}`;
}
};
user.greet(); // "Hi, I'm Alice"When you call user.greet(), 'this' points to 'user' — the object before the dot.
💡 this = object before the dot
1 / 3
Getters & Setters
Computed properties that look like regular access.
const user = {
firstName: "Alice",
lastName: "Smith",
// Getter — accessed like a property:
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
// Setter — assigned like a property:
set fullName(value) {
const [first, last] = value.split(" ");
this.firstName = first;
this.lastName = last;
}
};
user.fullName; // "Alice Smith" (calls getter)
user.fullName = "Bob Jones"; // calls setter
user.firstName; // "Bob"get
Runs when you read the property
set
Runs when you assign to the property
Built-in Object Methods
Utilities for working with any object.
const user = { name: "Alice", age: 28, role: "dev" };
// Keys, values, entries:
Object.keys(user); // ["name", "age", "role"]
Object.values(user); // ["Alice", 28, "dev"]
Object.entries(user); // [["name","Alice"],["age",28],...]
// Merge/copy:
Object.assign({}, user, { age: 29 });
// { name: "Alice", age: 29, role: "dev" }
// Freeze (make immutable):
const frozen = Object.freeze({ x: 1 });
frozen.x = 2; // silently fails (or throws in strict)
// Create from entries:
Object.fromEntries([["a", 1], ["b", 2]]);
// { a: 1, b: 2 }| Method | Returns |
|---|---|
| Object.keys(obj) | Array of key strings |
| Object.values(obj) | Array of values |
| Object.entries(obj) | Array of [key, value] pairs |
| Object.freeze(obj) | Frozen object (immutable) |
| Object.assign(target, ...) | Merged target object |
Computed Properties
Use expressions as property names.
// Dynamic keys with []:
const field = "email";
const user = {
name: "Alice",
[field]: "alice@test.com", // key = "email"
};
// { name: "Alice", email: "alice@test.com" }
// Useful for building objects dynamically:
function createPair(key, value) {
return { [key]: value };
}
createPair("color", "blue"); // { color: "blue" }
// With template literals:
const prefix = "data";
const obj = {
[`${prefix}Id`]: 1,
[`${prefix}Name`]: "test",
};
// { dataId: 1, dataName: "test" }FAQ
Common questions about object methods.