I had no clue what I did in the contact list


#1

var friends = {
bill: {
firstName: 'Bill',
lastName: 'Gates',
number: '(206) 555-5555',
address: ['One Microsoft Way', 'Redmond', 'WA', '98052']
},
steve: {
firstName: 'Steve',
lastName: 'Jobs',
number: '(206) 333-4242',
address: ['One Infinite Loop', 'Cupertino', 'CA', '95123']
}
};

var list = function (contacts) {
for (var people in friends) {
console.log(people)
}
}

var search = function (name) {
for (var people in friends) {
if (friends[people].firstName === name) {
console.log(friends[people])
return friends[people]
} else {
console.log("No contacts found with the name:" + name)
}
}
}

search("Bill")

Can someone explain to me how this code works? First, I don't understand why we have a comma after every object in the object array. Second, what is the for loop doing in this specific script. Third, for the search function, what is the if/else statement doing? Thanks for taking your time to help.


#3

Why do we have a comma after every object in the object array?

Arrays are always represented by comma separated lists to denote individual values. For example, an array can look like this:
{"red", "blue", "green"}
or like this:
{1, 2, 3}
or like this:

{
    banana:{colour: "yellow", type: "fruit"}, 
    carrot:{colour: "orange", type: "vegetable"}
}

It's simply a way of letting computers (and humans) differentiate between the different entries in an array.

What is the for loop doing in this specific script?

There are two loops in this code. The first loop (contained in the function 'list') simply iterates through each entry in the array 'friends' and logs the value to the console.

What is the if/else statement doing?

The other function 'search' takes a name argument (for example, "Bill") - this then loops through the list of people in the friends array and checks whether the first name of each person matches "Bill".

If it does, it logs that person's details to the console. Otherwise (if no match is found) the else clause is triggered, and a message is displayed.