Profile lookup problem...why brackets and not dot notation?

For the Profile Lookup Problem. Can anyone tell me why I need the brackets instead of dot notation for: return contacts[i][prop];

why doesn’t: return contacts[i].prop work?

// here is my full code to solve the problem…

function lookUpProfile(firstName, prop){
//Only change code below this line

for( var i = 0; i < contacts.length; i++ ){
if( firstName == contacts[i].firstName ) {
if( contacts[i].hasOwnProperty( prop ) ) {
return contacts[i][prop]; //need [] around prop b/c it is an index?
} else {
return “No such property”;
}
}
}
return “No such contact”;

Hey, that is because prop is not the actual key you are looking for. You are looking for the value the variable prop holds. So prop holds a value, instead of being a value itself. Using the dot notation JS will expect an actual value (a string). Using bracket notation JS allows you to use a variable.

Example:
var prop = "album"; // suppose there is a key "album"
In this case object[prop] is equal to object["album"] which is again equal to this dot notation: object.album.

Hope that makes sense.

3 Likes

Awesome, thanks so much. Great explanation and I totally get it now. = )

1 Like