Can somebody please explain the use of [] in this line of code?

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

Double check this lesson

I think you’re confusing two different types of loops – the classic for loop, and a newer(ish) for…in loop.

Here is the relevant MDN pages for each:

For loop
For…in loop

Note that this is an opportunity to show how explicit and semantic variable names can help code readability –

consider:

for (let counter = 0; counter < contacts.length; counter++) {
  // .. do things
}

vs:

for (const contact in contacts) {
  // do stuff
}
1 Like

Ok… I get it…

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…

I think it would work more like this:

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:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.