Hi, I really need some help understanding dot and bracket notation In lesion 101 under basic Java script titled Profile Lookup, . I thought the two were interchangeable except when it comes to accessing properties from objects. I know that bracket notation is used when your object property has a space and I thought that was the only difference.
The full code is down below but this is main part I don’t understand.
I do not understand why I cannot change
if(contacts[i].firstName === name) // into
if(contacts[i][firstName] === name)
or why I cannot change
return contacts[i][prop] || “No such property”; // into
return contacts[i].prop || “No such property”; // without getting an error
I would really appreciate it if someone could explain why these changes cause an error.
The full code is down below:
function lookUpProfile(name, prop){
for (var i = 0; i < contacts.length; i++) {
if(contacts[i].firstName === name) {
return contacts[i][prop] || “No such property”;
}
}
return “No such contact”;
}____
Full code below
//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["JavaScript", "Gaming", "Foxes"]
}
];
function lookUpProfile(name, prop){
for (var i = 0; i < contacts.length; i++) {
if(contacts[i].firstName === name) {
return contacts[i][prop] || "No such property";
}
}
return "No such contact";
}
// Change these values to test your function
lookUpProfile("Akira", "likes");