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

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";

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.

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]
3 Likes

Understood perfectly!!! thanks!

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") {