Profile Lookup -- "firstName" undefined when p<5

Can someone please help me understand the difference between the following two versions of code for the Profile Lookup challenge?

I wrote it like this:

//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){
// Only change code below this line
for (var p = 0; p <= 4; p++){
  if (contacts[p].firstName === name){
    if (contacts[p].hasOwnProperty(prop)){
    return contacts[p][prop]} else {return "No Such Property"};
    }
  }
return "No Such Contact"
}
// Only change code above this line

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

If I put in bob, a non-existent name, the function throws me “firstName” is undefined error.

But if I change p<=4 in the for loop to p < contacts.length the error goes away. Can you please help me understand why my function doesn’t work with p<=4 ? Thank you!

There is no contacts[4] because contacts only has a length of 4. That means that contacts[4] is undefined and you get an error when you try to lookup contacts[4].firstName.

Oh my goodness! Of course, because I’m looking up an index. I thought my problem was a lot more complicated than that! x) I tried p <= 3 and it works. Thank you so much!

I’m glad I could help. Happy coding!