Welcome! Today, we will explore creating a simple address book application using JavaScript Map. This task will help you understand manipulating Map in JavaScript, focusing on adding, retrieving, and deleting entries. By the end of this lesson, you'll have a solid grasp of these fundamental operations.
In this task, we will implement three methods to manage our address book:
addContact(name, phoneNumber): Adds a new contact. Returnsfalseif the contact already exists; otherwise, it adds the contact and returnstrue. In this task, let's assume phone numbers do not change, so it's not allowed to overwrite the existing contact's number.getContact(name): Retrieves the phone number for a givenname. Returnsundefinedif the contact does not exist.deleteContact(name): Deletes a contact with the givenname. Returnstrueif the contact exists and is deleted,falseotherwise.
Let's break down each method in detail in the next sections.
This method adds a new contact to the address book with the given name and phoneNumber. If the contact already exists, it returns false. Otherwise, it adds the contact and returns true.
Question: Why do you think we need to check if the contact already exists?
Answer: To avoid duplicating existing entries. Also, if a contact with the same name already exists, we shouldn't allow overwriting its phone number in this method, as it's only for creation. Here is the method implementation:
In this method:
- We verify if the contact already exists using
if (this.contacts.has(name)). - If it exists, we return
false. - If it doesn't exist, we add it to our
Mapand returntrue.
