Contacts[i].prop vs contacts[i][prop]

Tell us what’s happening:
Describe your issue in detail here.

Why doesn’t contacts[i].prop work here? I looked up the solution and it uses contacts[i][prop]. I thought dot notation could be used to retrieve a property, once the counter variable points to the numbered object in an array.

  **Your code so far**

// Setup
const 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) {
// Only change code below this line
for (let i = 0; i < contacts.length; i++) {
  if (name === contacts[i].firstName) {
    if (contacts[i].hasOwnProperty(prop)) {
      return contacts[i].prop
    }
    else {
      return "No such property"
    }
  }
}
return "No such contact"
// Only change code above this line
}

lookUpProfile("Akira", "likes");
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36

Challenge: Profile Lookup

Link to the challenge:

You’ll notice that none of the objects have a property named “prop”.

1 Like

So the dot notation I used wouldn’t be applicable since it’s directly looking for a property named “prop”? Wouldn’t the input (prop), be replaced by the function input such as used in the example? Prop wouldn’t be replaced by whatever is in the input?

If the user entered “likes”, wouldn’t prop just be a variable that would call the string “likes” if used in the indices?

contacts[i].prop > contacts[0] would refer to the first object,

then contacts[0].prop would turn into contacts[0].likes.

This is where I’m getting confused.

So the dot notation I used wouldn’t be applicable since it’s directly looking for a property named “prop”?

Correct

1 Like

You always must use the exact, literal name of the property for dot notation.

1 Like

Here’s the relevant lesson:

Another use of bracket notation on objects is to access a property which is stored as the value of a variable.


Also,

Dot notation is what you use when you know the name of the property you’re trying to access ahead of time.

3 Likes