# Kindly explain the 'add' function.I did not understand the 'contacts[contacts.length]' part?

#1

var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones@example.com"
};

var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson@example.com"
};
var add = function(firstName, lastName, phoneNumber, email) {
contacts[contacts.length] = {
firstName: firstName,
lastName: lastName,
phoneNumber: phoneNumber,
email: email
};
};

var contacts = [bob, mary];

function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
}

function list() {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
}
/*Create a search function
then call it passing "Jones"*/
var search = function(lastName) {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
if (contacts[i].lastName === lastName) {
printPerson(contacts[i]);
}

}
};
//search("Jones");

list();

#2

The purpose of add is to add a person to the contacts list.
Let's say that the list currently contains bob and mary. Thus, the list can be represented as [bob, mary].

When we call add("Anushree", "Jayram", "888-8888", "anu.jay@example.com"), we want to add the person with these specifications to the end of the list. Let's see what happens:

What is contacts.length equal to? 2.
What is contacts[2] equal to? Nothing. We are at the end of the list. (start counting from 0)
What happens when we set contacts[2] equal to something? We fill the empty space. We are appending to the list.

So this function correctly appends a person to the list.

#3

thanks for the explanation