Bracket notation vs dot notation when iterating through arrays nested in a object


i need a language that can act as a front end for solidity, so i am learning js. Im completing the js course and am wondering why this line of code isnt iterable with bracket notation.

(name === contacts[i][firstName])

ive included a snip bit of the code below. I have figured out the answer but still wish to know why bracket notation isnt applicable in this situation.

The code in question is at the bottom of this post

const contacts = [
firstName: “Akira”,
lastName: “Laine”,
number: “0543236543”,
likes: [“Pizza”, “Coding”, “Brownie Points”],
firstName: “Harry”,
lastName: “Potter”,
number: “0994372684”,
likes: [“Hogwarts”, “Magic”, “Hagrid”],

function lookUpProfile(name, prop) {

for (let i = 0; i < contacts.length; i++) {
if (name === contacts[i][firstName]) {

You are able to use bracket notation however you have a small typo. When using bracket notation, if you don’t include quotes, Javascript thinks you are looking up a key name by variable (such as when you may not know the key name and are receiving it from somewhere else) rather than looking up a specific key name. You would need to change your code to contacts[i][‘firstName’] to lookup the data for your if statement.

1 Like

so in “contacts[i][firstName]”, JS is trying to search for a variable firstName that doesnt exist, instead of the key - value firstName. right?

Yup, exactly!

An example of when you would want to use the variable instead could be a function that’s used to return a user selected key-value pair.

const object = {‘a’:1, ‘b’:2}

function getValue(key) {
return object[key])

1 Like

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