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!