Profile Lookup Question

Hi Folks,

I’m not clear why bracket notation works for this, but dot notation doesn’t. See comments in code below. Aren’t these interchangeable?

Thanks,
Starr

function lookUpProfile(firstName, prop){
// Only change code below this line
  for(var i=0; i < contacts.length; i++){
    if(contacts[i].firstName === firstName){
      if(contacts[i].hasOwnProperty(prop)){
        return contacts[i][prop]; //THIS WORKS
        return contacts[i].prop; //THIS DOESN'T WORK
      }else {
        return "No such property";
      }
    }
  }
  return "No such contact";

// Only change code above this line
}

// Change these values to test your function
lookUpProfile("Kristian", "lastName");

Link to the challenge:
https://www.freecodecamp.org/challenges/profile-lookup

Because when you use dot notation, you have to use the exact name of the property. Only bracket notation allows you to use a variable as a property name.

Read:

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

In addition to the links @elisecode247 provided you, you can also review the following FCC challenge on this topic which you would have already completed in the Basic JavaScript section.

https://www.freecodecamp.org/challenges/accessing-objects-properties-with-variables

Thanks, everyone, for the answer, resources and code readability tips :slight_smile: Much appreciated!