Question 7, got it right but code seems redundant


#1

I got Question 7 right, but I don't understand the coding syntax. Here is what I wrote:

var friends = {
bill:{
firstName: "Bill",
lastName: "Clinton",
number:69,
address:["1600 Pennsylvania Avenue","Washington,D.C."]
},
steve:{
firstName:"Steve",
lastName:"Colbert",
number:51,
address:["500 Freedom Street","America"]
}
};

var list = function (friends) {
for (var firstName in friends) {
console.log(firstName);
}
};

var search = function (name) {
for (var firstName in friends) {
** if (friends[firstName].firstName === name) {**
console.log(friends[firstName]);
return friends[firstName];
}
}

}

What confuses me is "friends[firstName].firstName". This seems really redundant to me. Why do I have you write out "firstName" twice?


#2

I have the exact same code and same question :slightly_smiling:


#3

Perhaps it makes more sense if you rename the firstName in the loop to key


#4

friends[firstName].firstName

in this line the friends is the object.
the firstname within the [] is the key used in the for loop(its better if you named it key in the for loop). For example when I have an object such as :
var friends = {
bill:{
firstname: "Bill",
},
}

the key is reffering to the object bill inside friends not the firstname Bill which is inside bill, inside friends.
And finally the firstname is reffering to the "Bill" inside the bill object.
Hope you get it now


#5

Also, why is return used? Is that just in place to "route" back to the contact so the rest of the information can be logged?


#6

You are using firstName for 2 different keys, which shouldn't be the case. You could write something like this instead:

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

Check out the long answer and my explanation on keys here: http://discuss.codecademy.com/t/contact-list-6-list-em-all/23792/4