AI Hints
Home›JavaScript Tutorial›Practice: Objects
JavaScript · Lesson 67 of 138

Practice: A Contact Book

Objects in action.

⏱ 2 min read▶ Video at 1:21:35🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Let's build a little contact book. An object whose methods add contacts, find them, and list them alphabetically. It uses objects, arrays, methods, and this, all together.

Practice: A Contact Book
From the video: Practice: A Contact Book
  • A little contact book
  • Add, find, list
  • Everything together

The contact book

Contacts is an array of objects. Add pushes a new contact, and returns this, so calls can be chained. Find searches by name, ignoring capital letters. And list sorts by name, with local compare, and formats each line. Run it.

app.jsjavascript
const book = {
  contacts: [],
  add(name, phone) {
    this.contacts.push({ name, phone });
    return this;
  },
  find(name) {
    return this.contacts.find(c => c.name.toLowerCase() === name.toLowerCase());
  },
  list() {
    return this.contacts.toSorted((a, b) => a.name.localeCompare(b.name))
      .map(c => `${c.name}: ${c.phone}`);
  },
};

book.add("Zoe", "555-0101").add("Ana", "555-0102").add("Max", "555-0103");
console.log(book.find("ana"));
console.log(book.list());
Output
{ name: 'Ana', phone: '555-0102' }
[ 'Ana: 555-0102', 'Max: 555-0103', 'Zoe: 555-0101' ]

A shorthand

Notice name comma phone, inside the curly braces. When a key and a variable have the same name, you can write it just once. That's called shorthand property names. And returning this from a method allows chaining, like add, then add, then add.

keyvalue
{ name, phone }shorthand properties
return thisallows chaining
localeComparesort names
toLowerCasecase-insensitive find

Summary

We built a contact book with methods, this, shorthand properties, and chaining. Next, counting words with an object.

Key takeaways
  • Methods use this
  • return this to chain
  • Shorthand { name }
Next up: Practice: A Word Counter — objects as tallies