Problem in accessing property using . operator

Problem in accessing property using . operator
0

#1

If I use the following code, it’s working. But if I replace contacts[i][prop] with contacts[i].prop, the first 3 test cases do not get satisfied. Can someone please explain why is this happening?

var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    }
];


function lookUpProfile(firstName, prop){
for(var i=0;i<4;i++)
  {
    if(contacts[i].firstName==firstName)
      {
        if(contacts[i].hasOwnProperty(prop))  
          return contacts[i][prop];
        else
          return "No such property";
      }
  }
  return "No such contact";
}

#2

contacts[i].prop is looking for a property in the objects that’s literally named prop. There’s no such property in the contact objects.

You use bracket notation when the property that you want to look up is stored in a variable (like in contacts[i][prop]).