can someone explain why this solution would not work for the challenge? Why do I need to exit the For-Loop if the first If condition isn’t met? Why can’t I just return ‘No such property’ with an Else statement within the For-Loop?
For example if I run the function lookUpProfile(“Kristian”, ‘lastName’), the input “Kristian” meets the criteria for the 1st If-statement and then moves down to the nested If-statement and then finally execute and return contacts[i][prop]? Why am I getting ‘No such contact’ even though the 1st If-statement’s criteria is met?
//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 (let i = 0 ; i < contacts.length; i++){
if (contacts[i].firstName === name){
if (contacts[i].hasOwnProperty(prop)){
return contacts[i][prop]
} else {
return 'No such property'
}
} else {
return 'No such contact'
}
}
}
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop