Methods
A function stored on an object is a method, and it lets an object carry behaviour alongside its data.
Method shorthand defines a function as a property. Inside it, this refers to the object the method was called on. Object.keys, values and entries turn an object into arrays you can loop over.
EXERCISE
1Functions That Belong to an Object
Storing a function as a property keeps the behaviour next to the data it operates on.
Method shorthand, which is how you will write them:
const cart = {
items: [],
add(item) {
this.items.push(item);
},
total() {
return this.items.reduce((sum, i) => sum + i.price, 0);
},
count() {
return this.items.length;
},
};
cart.add({ name: "Tea", price: 40 });
cart.add({ name: "Coffee", price: 120 });
console.log(cart.count()); // 2
console.log(cart.total()); // 160
this refers to the object the method was called on:
const user = {
first: "Ada",
last: "Lovelace",
fullName() {
return `${this.first} ${this.last}`;
},
};
console.log(user.fullName()); // Ada Lovelace
// Inside fullName, `this` is `user`, so this.first is "Ada".
The longer form, which means the same thing:
const user2 = {
first: "Ada",
fullName: function () {
return this.first;
},
};
console.log(user2.fullName()); // Ada
And the form that does not work here:
const user3 = {
first: "Ada",
fullName: () => `${this.first}`, // arrow: no `this` of its own
};
console.log(user3.fullName()); // "undefined"
An arrow takes this from the surrounding code, which for an object literal is not the object. Use method shorthand for methods.
Pro Tip:
thisdepends on how a method is called, not where it was written, and that is the single most confusing rule in the language. For the shapes in this course the rule is simple: called asobject.method(),thisis that object. Intermediate JavaScript covers the cases where it is not.
EXERCISE
2Turning an Object into Arrays
Three built-in methods convert an object's contents into arrays, which lets you use everything from Unit 7 on it.
keys, values and entries:
const scores = { ada: 90, grace: 72, alan: 85 };
console.log(Object.keys(scores)); // [ 'ada', 'grace', 'alan' ]
console.log(Object.values(scores)); // [ 90, 72, 85 ]
console.log(Object.entries(scores));
// [ [ 'ada', 90 ], [ 'grace', 72 ], [ 'alan', 85 ] ]
Which means array methods now work on objects:
const scores = { ada: 90, grace: 72, alan: 85 };
console.log(Object.keys(scores).length); // 3 how many entries
const total = Object.values(scores).reduce((sum, n) => sum + n, 0);
console.log(total); // 247
const passed = Object.entries(scores)
.filter(([, score]) => score >= 80)
.map(([name]) => name);
console.log(passed); // [ 'ada', 'alan' ]
That [, score] pulls the second item out of each pair and ignores the first.
Looping over an object:
const scores = { ada: 90, grace: 72 };
for (const [name, score] of Object.entries(scores)) {
console.log(`${name}: ${score}`);
}
// ada: 90
// grace: 72
// for-in does the same for keys, and this is where it belongs:
for (const name in scores) {
console.log(`${name}: ${scores[name]}`);
}
Going back the other way:
const pairs = [["a", 1], ["b", 2]];
console.log(Object.fromEntries(pairs)); // { a: 1, b: 2 }
// Which makes transforming an object a three-step move:
const doubled = Object.fromEntries(
Object.entries({ a: 1, b: 2 }).map(([k, v]) => [k, v * 2]),
);
console.log(doubled); // { a: 2, b: 4 }
Objects have no map or filter of their own, and these three methods are how you borrow the array ones. Object.entries into an array method and Object.fromEntries back again is the standard way to transform an object, and it is worth recognising because it appears constantly in real code.
EXERCISE
3Objects of Functions, and Shared Behaviour
Grouping related functions on an object is a useful pattern in its own right, even when there is no data to go with them.
A namespace of related functions:
const money = {
toPaise(rupees) {
return Math.round(rupees * 100);
},
format(paise) {
return `Rs ${(paise / 100).toFixed(2)}`;
},
addTax(paise, rate = 0.18) {
return Math.round(paise * (1 + rate));
},
};
const paise = money.toPaise(19.99);
console.log(money.format(money.addTax(paise))); // Rs 23.59
This is exactly the shape of the built-in objects you already use: Math.round, JSON.stringify, Object.keys.
A method that returns the object allows chaining:
const builder = {
parts: [],
add(text) {
this.parts.push(text);
return this; // hand the object back
},
build() {
return this.parts.join(" ");
},
};
console.log(builder.add("Hello").add("there").build()); // Hello there
Methods can call each other through this:
const account = {
balance: 0,
deposit(amount) {
this.balance += amount;
return this;
},
withdraw(amount) {
if (amount > this.balance) {
console.log("Insufficient funds");
return this;
}
this.balance -= amount;
return this;
},
report() {
console.log(`Balance: ${this.balance}`);
},
};
account.deposit(500).withdraw(200).report(); // Balance: 300
account.withdraw(1000); // Insufficient funds
Pro Tip: Returning
thisfrom a method is how method chaining works, and you have been using it all along without noticing, because that is why" hi ".trim().toUpperCase()reads left to right. It is a small pattern with a large payoff in readability once your objects have several related operations.
