Not sure when to use . and when to use [ ] while accessing Objects. Why am I getting an error

Not sure when to use . and when to use [ ] while accessing Objects. Why am I getting an error
0

#1

Can you pl. help me understand what is the reason for the errors. I have commented the reason in CAPS on the particular lines.

Objects for Lookups Topic

function phoneticLookup(val) {
  var result = "";

  // Only change code below this line
  
  var lookup = {
    "alpha": "Adams",
    "bravo": "Boston",
    "charlie": "Chicago",
    "delta": "Denver",
    "echo": "Easy",
    "foxtrot": "Frank"
  };
  
  return lookup[val];  //  CANNOT USE lookup.val as it gives an error. NOT ABLE TO UNDERSTAND WHY
  return result;
  // Only change code above this line
  
}

// Change this value to test
phoneticLookup("charlie");

Profile Look up

function lookUpProfile(firstName, prop){
// Only change code below this line
 
  for (i=0; i<contacts.length; i++)
    {
       if (firstName==contacts[i].firstName) /*CANNOT USE contacts[i][firstName] as it gives an error. NOT ABLE TO UNDERSTAND WHY */
         {
            if(contacts[i].hasOwnProperty(prop))
              {
                return contacts[i][prop];
              }
           else
             {
               return "No such property";
             }
         }
    }
      
   return "No such contact";

#2

#3

I did not understand.

Lets take the example two for instance.

contact[i][firstName] and contact[i].firstName both refer to the same prop. But I get and error when I use brackets and not when I use the . This is exactly the opposite in the first example.


#4

No they don’t: contact[i].firstName is the same as contact[i]["firstName"].

Whatever you put after the dot is taken literal. So contact[i].firstName searches for property called firstName. Inside the brackets you can put an expression:

var property = "firstName";
var obj = {
  firstName: "Bob"
}
// obj.firstName === obj["firstName"] === obj[property]

#5

Understood perfectly!!! thanks!


#6

You have to use the brackets if your property has a space, correct?
.dot notation will not work in that regard.

what about when you are using both with objects
:sunglasses:
if ( this[key].type == "ferrari") {