So I always think of the bracket as related to arrays, and also a way to get down to a certain item position from a json file or an object…
Obviously the code below works… but why is it done this way with the brackets …
// function lookUpProfile(name, prop) {
// for (let x = 0; x < contacts.length; x++) {
// if (contacts.firstName === name) {
// if (contacts.hasOwnProperty(prop)) {
// return contacts[prop];
// } else {
// return “No such property”;
// }
// }
// }
// return “No such contact”;
// }
and not this way with the dot notation?
function lookUpProfile(name, prop) {
for (let x in contacts) {
if (x.firstName === name) {
if (x.hasOwnProperty(prop)) {
return x.prop;
} else {
return “No such property”;
}
}
}
return “No such contact”;
}
I think my code isn’t being display correctly on the post… but I think the reason for the above code to use the brackets [ ] instead of dot notation is because I am inserting a variable in the code …
I often just use the dot notation to get values from json files for example, and then use the bracket with a number [2] to reach an specific item …
But for this specific lesson I wasn’t able to make it work with the dot notation…
If you replace the “for” loop for the “for in” still works … the problem was trying to pass the variable with dot notation, which I haven’t figured out how to do it… but indeed there is a lesson on how to pass a variable with the bracket notation…
You can’t pass variables using dot notation, that always assumes you’re referencing a property name directly. See this stack overflow post for more detail: