0

My code do not run correctly but I could not figure out a mistake in my code. Is there something that I am missing?

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(firstName, prop){ for (i = 0; i < contacts.length; i++) { if (firstName === contacts[i].firstName) { if (contacts[i].hasOwnProperty(prop)) { return contacts[i].prop; } else { return "No such property"; } } else { return "No such contact"; } } } lookUpProfile("Harry", "likes");

17th Sep 2017, 4:03 AM
Trưởng Nguyễn
Trưởng Nguyễn - avatar
3 Respuestas
+ 7
Your mistake is in your last 'else' statement (from the first 'if', as the second is nested): you are in a loop to verif if each item is equal to the searched value, but if it's not the first item you return the error message so exit from loop and doesn't continue testing other items ^^ @Calvin solution doesn't work as expected, and return 'undefined' value in case of contact not found... rather do: function lookUpProfile(firstName, prop){ for (i = 0; i < contacts.length; i++) { if (firstName === contacts[i].firstName) { if (contacts[i].hasOwnProperty(prop)) { return contacts[i][prop]; } else { return "No such property"; } } return "No such contact"; } ... so the error message is returned only after all items were tested, and none found (else value will have been already returned breaking the loop)
17th Sep 2017, 6:09 AM
visph
visph - avatar
17th Sep 2017, 4:23 AM
Calviղ
Calviղ - avatar
+ 1
I have understood, thank you all!! 😅😅
17th Sep 2017, 6:50 AM
Trưởng Nguyễn
Trưởng Nguyễn - avatar