Hey yo, good evening,
I have doubts concerning my knowledge of accessing object’s properties.
I was doing this ‘Basic Javascript’ challenge for about 2 hours, then i looked up the solution. It differed only in one thing:
The solution:
function lookUpProfile(firstName, prop){
for (var i = 0; i< contacts.length; i++){
if (contacts[i].firstName === firstName) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
}
My code that didn’t get a pass:
function lookUpProfile(firstName, prop){
for (var i = 0; i< contacts.length; i++){
if (contacts[i][firstName] === firstName) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
}
I edited formatting so it looks alike.
Now, what’s different is the first if statement;
solution:
if (contacts[i].firstName === firstName)
mine:
if (contacts[i][firstName] === firstName)
I thought that bracket notation is more universal (useful for example when the key consists of two words), and i can use it any time.
Why did bracket notation not worked here?