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

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

#1

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”;


#2

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.


JavaScript: About Accessing Nested Objects through a Loop
Using Objects for Lookups - with dot notation
Not sure when to use . and when to use [ ] while accessing Objects. Why am I getting an error
#3

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