Profile Lookup w/ dot vs. bracket

Profile Lookup w/ dot vs. bracket
0.0 0

#1

Ok, question about dot versus bracket notation in this challenge.

return contacts[i].prop; does not work while return contacts[i][prop]; does.

We’re IN the array, hence the contacts[i]. This finds the “i” item in the array, which is an object. Because I’m now in an object, dot notation should work. It actually works in my if statement where if (firstName == contacts[i].firstName).

Is this a flaw in the challenge (i.e. would work in the real world)? If not, can someone please explain what I’m missing. Thanks!

As reference, code that doesn’t work:

function lookUpProfile(firstName, prop){
// Only change code below this line
for (i = 0; i < contacts.length; i++) {
if (firstName == contacts[i].firstName) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i].prop;
} else {
return “No such property”;
}
}
} return “No such contact”;
// Only change code above this line
}

Code that DOES work:

function lookUpProfile(firstName, prop){
// Only change code below this line
for (i = 0; i < contacts.length; i++) {
if (firstName == contacts[i].firstName) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return “No such property”;
}
}
} return “No such contact”;
// Only change code above this line
}


#2

Remember that prop is a variable, which is why it works with contacts[i][prop]. When you write contacts[i].prop, you are referring to a property in the object (contacts[i]) called “prop”. In bracket notation, this would be the equivalent of contacts[i][“prop”].

To summarize, the following statement is true:

contacts[i]["prop"] === contacts[i].prop