Object methods
An object method is a function stored as a property of an object. Methods let an object carry behaviour alongside its data, so a cart object can both hold items and calculate its own total. The word "object methods" also covers the built-in helpers on Object, such as Object.keys() and Object.entries(), that let you inspect and transform any object. This lesson looks at both.
Defining methods and using this
The shorthand syntax name() { ... } inside an object literal is the modern way to define a method. Inside it, this refers to the object the method was called on, so the method can read and update the object's other properties.
const cart = {
owner: 'Meera',
items: [],
add(name, price, qty = 1) {
this.items.push({ name, price, qty });
return this; // allows chaining
},
total() {
return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
};
cart.add('Pen', 20, 3).add('Notebook', 60);
console.log(cart.total()); // 120
// Built-in helpers on Object
const prices = { pen: 20, notebook: 60, bag: 900 };
Object.keys(prices); // ['pen', 'notebook', 'bag']
Object.values(prices); // [20, 60, 900]
Object.entries(prices); // [['pen', 20], ['notebook', 60], ['bag', 900]]
const discounted = Object.fromEntries(
Object.entries(prices).map(([k, v]) => [k, v * 0.9])
);
const merged = Object.assign({}, prices, { pen: 25 });
const frozen = Object.freeze({ gst: 0.18 });
Useful helpers on Object
| Method | Returns |
|---|---|
Object.keys(obj) | Array of the object's own property names |
Object.values(obj) | Array of the property values |
Object.entries(obj) | Array of [key, value] pairs, ideal for looping or mapping |
Object.fromEntries(list) | A new object built from pairs |
Object.assign(target, ...sources) | The target, after copying properties into it |
Object.freeze(obj) | The same object, now unable to change at the top level |
Object.hasOwn(obj, key) | Whether the object itself has that property |
The entries and fromEntries pair is the standard way to transform every value in an object, as discounted shows. The spread syntax { ...prices, pen: 25 } is a shorter alternative to Object.assign for copying.
Looping over an object usually starts with one of these helpers. for (const [key, value] of Object.entries(prices)) { ... } gives you both parts of each property in a readable way. The older for...in loop also visits inherited enumerable properties, which is why modern code prefers the Object helpers. Remember that all three helpers list only the object's own enumerable string keys, not symbols.
Losing this when a method is detached
The value of this depends on how a method is called, not where it was written. cart.total() works, but const t = cart.total; t(); calls the function on its own, so this is undefined in strict mode and the code throws. The same happens when you pass a method as a callback, for example setTimeout(cart.total, 100). Fix it with cart.total.bind(cart) or an arrow wrapper: () => cart.total().
Writing the method itself as an arrow function does not help, because arrows never have their own this.
Shallow, not deep
Object.assign, spread and Object.freeze all work one level deep. Copying cart with spread gives a new object, but both copies share the same items array. Freezing an object does not freeze the arrays or objects inside it. Use structuredClone() when you need a full independent copy.
When you need an object that should not be changed by accident, such as configuration values, Object.freeze is a quick safeguard; assignments to it fail silently in normal code and throw in strict mode.
Takeaway
Define methods with shorthand syntax, call them through the object so this is correct, and use Object.keys, values and entries to work with an object's properties.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.