1
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 < contacts.length; i++){
if (firstName === contacts[i].firstName) {
if (contacts[i][prop]) {
    return contacts[i][prop];
} else {
    return "No such property";
  }
}
}
return "No such contact"; 
}
lookUpProfile("Akira", "likes");

This code runs perfectly. but if i use if (firstName === contacts[i] [firstName]) instead of if (firstName === contacts[i].firstName), it doesn't work. Why? Since either dot or bracket notation both can be used for accessing the objects property.

Rajat Chauhan
  • 13
  • 1
  • 6
  • 3
    Possible duplicate of [JavaScript property access: dot notation vs. brackets?](http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – Thilo Sep 26 '16 at 05:37
  • agree on the duplicate and I think this answer is more approrpriate to your question: http://stackoverflow.com/a/4968460/1695393 – dubes Sep 26 '16 at 05:47

1 Answers1

0

The brackets are for variables. If you want to use them with String literals, you could, but you have to quote them: contacts[i]['firstName']. But unless the property name contains restricted characters (such as another dot or a space), that is just silly.

Note that you already used it with i (which is a variable) to get the i-th element (and not a property called i).

Thilo
  • 257,207
  • 101
  • 511
  • 656