Spoiler alert! This question is about the last main challenge in the Basic Javascript course. If you’re working on the solution and you want to work it out for yourself, leave this page now!
I thought I’d solved this problem but for every combination of parameters I passed to the function I got “No such contact”:
console.log(lookUpProfile("Sherlock", "lastName")) // No such contact (Should be: Holmes)
console.log(lookUpProfile("Sherlock", "likes")) // No such contact (Should be: "Intriguing Cases", "Violin")
console.log(lookUpProfile("Sherlock", "hobbies")) // No such contact (Should be: No such property)
console.log(lookUpProfile("Watson", "likes")) // No such contact (true)
So I went to the ‘hints’ page. Hint 1 - I’d done that ok. Hint 2 - I done that one as well.
So I looked at the final hint: put the final return statement (“No such contact”) outside of the for loop as a catch-all for when the conditions inside the loop weren’t met.
And, of course, it worked.
But I’m still scratching my head about why my solution doesn’t work.
My (wrong) solution:
function lookUpProfile(name, prop){
for(var 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 {
// Incorrect position - "No such contact" is returned for everything
return "No such contact"
}
}
// Correct position
// return "No such contact"
}
I see the logic of my solution as:
if: firstname exists continue on to:
----- if: props exist then:
---------- return the value of that property
----- else:
---------- report that property as non-existent
else: (as firstname has not been found)
----- report firstname as non-existent
Could anyone explain the flaw in my logic?