Objects & The Difference between Dot Notation Vs Bracket Notation

Hi, I really need some help understanding dot and bracket notation In lesion 101 under basic Java script titled Profile Lookup, . I thought the two were interchangeable except when it comes to accessing properties from objects. I know that bracket notation is used when your object property has a space and I thought that was the only difference.

The full code is down below but this is main part I don’t understand.
I do not understand why I cannot change
if(contacts[i].firstName === name) // into
if(contacts[i][firstName] === name)

or why I cannot change
return contacts[i][prop] || “No such property”; // into
return contacts[i].prop || “No such property”; // without getting an error

I would really appreciate it if someone could explain why these changes cause an error.

The full code is down below:


function lookUpProfile(name, prop){
for (var i = 0; i < contacts.length; i++) {
if(contacts[i].firstName === name) {
return contacts[i][prop] || “No such property”;
}
}
return “No such contact”;

}____

Full code below


//Setup
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(name, prop){
  for (var i = 0; i < contacts.length; i++) {
    if(contacts[i].firstName === name) {
      return contacts[i][prop] || "No such property";
    }
  }
  return "No such contact";
}

// Change these values to test your function
lookUpProfile("Akira", "likes");

I suggest reviewing Accessing Object Properties with Variables.

1 Like

Thank you so so very much!

I initially thought you were crazy at first and that you just gave me a bogus answer without reading my question. I spent a day stalling and didn’t listen to your advice because I convinced myself that I already knew what the lesson said and that there was no reason to go back. Sorry for doubting you, you link was just what I needed.

Thank you again.

I’m glad that I could help and that you found a solution. Happy coding!