Skip to the content

Project: contact book

JavaScript · Unit 7: Objects

Your contact book is an array of objects: each contact has a name and a phone. Adding a contact means doing a push on the array.

const contacts = [];
contacts.push({
  name: "Leo",
  phone: "555-0202",
});
console.log(contacts.length);
console.log(contacts[0].phone);

Prints

1
555-0202

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Complete the function that builds a new contact to add to the book.

  2. 2. Predict the output

    You look for Mia in the contact book. What does it print?

  3. 3. Write the code

    Write lookup(contacts, name), which returns the phone of the contact with that name, or "Not found" if there isn't one.

  4. 4. Write the code

    Write listAll(contacts), which returns an array of strings shaped like "Name: phone", in alphabetical order. For example, with Leo and Ava it gives ["Ava: 555-01", "Leo: 555-02"].

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →