7. Search for a friend - What is [prop] and why does it work?


#1


Before looking at a similar issue someone was having, my code read:

var search = function(name) {
for (var firstName in friends) {
if (friends.firstName === name) {
console.log(friends[firstName]);
return friends[firstName];
} else {
console.log("Friend not found.");
}
}
};

After looking at the solution, I replaced firstName with prop. Prior to, and including this lesson, we have not been taught 'prop.' Why does this work and what does this 'prop' value do for the code that referencing firstName does not?


var friends = {
    bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: "7757508821",
        address: ["8350 Cub Court", "Reno", "NV", 89506]
        },
    steve: {
        firstName: "Steve",
        lastName: "Jobs",
        number: "7759723290",
        address: ["9670 Oakley Ln", "Reno", "NV", 89521]
        }
};

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

var search = function(name) {
    for (var prop in friends) {
        if (friends[prop].firstName === name) {
            console.log(friends[prop]);
            return friends[prop];
        } else {
            console.log("Friend not found.");
        }
    }
};


#2

prop is just a variable which hold the properties inside your friends object:

var search = function(name) {
    for (var prop in friends){
       console.log(prop)
       console.log(friends[prop]) 
   }
}

in each run of the loop, prop gets assigned (in turn) the properties in friends object. prop could be named anything, but given it gets assigned properties, prop is a good choice for the variable name


#3

So, just to be perfectly clear, var prop in friends means that prop is assigned any of the properties below the friends variable, including the first name, last name, number and address fields?


#4

no, prop gets assigned the properties nested in friends:

bill
steve

the objects bill and steve.

this why you have .firstName in your if condition:

if (friends[prop].firstName === name)

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.