CodeBlanks Logo Icon CodeBlanks

Summary - Objects

Combine objects, methods and spread to write a phone book.

Summary - Objects

In this group you looked at objects from four angles: the literal syntax, property access (dot and bracket), computed properties for dynamic names, and methods for behaviour. The spread operator gave a short way to copy and merge.

You can combine these to build real data structures. A phone book, for example: contact objects gathered in a root object, methods to add contacts, and spread to update them.

In the final task you will write a small phone book. You will add a method to insert contacts and another to look them up by name. You will also use object spread and bracket access.

Practice Phone book object

Define an object named contacts. Its add(name, phone) method should insert a new contact via this[name] = phone. Add Ayşe with phone 5551, then print contacts['Ayşe'] with console.log.

Starter code

index.js
// Define contacts with an add method, add Ayşe, print the number

Sample solution

index.js
const contacts = { add(name, phone) { this[name] = phone; } };
contacts.add('Ayşe', '5551');
console.log(contacts['Ayşe']);

Expected output

5551

Practice Look up in the phone book

Define the contacts object as { Ayşe: '5551', Alex: '5552' }. Its lookup(name) method returns this[name]. Print the result of contacts.lookup('Alex') with console.log.

Starter code

index.js
// Define contacts with a lookup method, print Alex's number

Sample solution

index.js
const contacts = { Ayşe: '5551', Alex: '5552', lookup(name) { return this[name]; } };
console.log(contacts.lookup('Alex'));

Expected output

5552

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the concepts

Term Meaning
{ } Object literal
.name Dot access
[key] Computed/dynamic access
...obj Spread copy
greet() { } Method definition

2 How do you look up in a phone book?

  • Add a method
  • Walk with forEach
  • Copy with spread
  • Bracket access by name Correct answer

Explanation: since the book is an object, bracket access by name is the fastest lookup.

3 Update with spread

Question
const base = { a: 1, b: 2 };
const copy = { ____, c: 3 };
Answer
const base = { a: 1, b: 2 };
const copy = { ...base, c: 3 };

Explanation: ...base copies a and b, then c is added.

All lessons in Beginner