I was going through one of codeacademy's javascript exercisees and ran into this. The following code is given by codeacademy.
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "1",
address: ['abc', 'def', 'ghi']
},
steve: {
firstName: "Steve",
lastNAme: "Jobs",
number: "2",
address: ['abc', 'def', 'ghi']
}
};
var list = function(obj) {
for (var prop in obj) {
console.log(prop);
}
};
var search = function(name) {
for (var prop in friends) {
if (friends[prop].firstName === name) {
console.log(friends[prop]);
return friends[prop];
}
}
};
What I don't understand is, in the search function, why I need to write out 'friends[prop]' instead of just 'prop'. If the for/in loop is iterating through every property in friends(array?), why do I need to specify again what array each prop belongs to? Why can't I use the following code?
var search = function(name) {
for (var prop in friends) {
if (prop.firstName === name) {
console.log(prop);
return prop;
}
}
};