Accessing a value in an object using bracket notation didn't work here

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?

contacts is an array. The values of i are objects. They are inside an array, but still objects. Object properties are not the same as array elements.

But if you wanted to you could put them into an array.

The correct use of the bracket notation is with quotation marks, eg

contacts[i]["firstName"]

Dot notation is generally preferred, but if the key has a space in it, the bracket notation is necessary.

That, too. :sweat_smile:

Even though firstName is a variable not a string? It looks weird with parantheses

You’re not using the variable, you’re getting the property called “firstName”.

1 Like

Unquoted property names / object keys in JavaScript

1 Like

I think i get it , i was confused because argument passed to the function was also firstName.

Anyway - wow! so much help here, big thanks :smiley: