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

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

#1

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?


#2

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.


#3

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.


#4

That, too. :sweat_smile:


#5

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


#6

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


#7

Unquoted property names / object keys in JavaScript


#8

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: