#I need help trying to understand why my code isn’t working#
function lookUpProfile(name, prop) {
for (let i = 0; i < contacts.length; i++) {
if(name === contacts[i].firstName && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else if (name !== contacts[i].firstName) {
return "No such contact";
} else if (prop !== contacts[i].hasOwnProperty(prop)) {
return "No such property"
}
}
}
lookUpProfile("Akira", "likes");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/116.0
You are SO close. But we need to re-evaluate your for-loop logic. The problem you’re running into is that you are only ever evaluating the very first contact and then its returning something. You’ll want to refactor this so that you can account for this covering every contact if there’s no matches.
I edited your post slightly to fix the formatting of the post and your code.
It’s a good idea to learn to format your code well (mostly by proper indentation), as it makes it much easier to read and to debug.
You’ve got the right basic idea but the issue is the return statements within your for loop. The first return is fine because, if you find a matching contact and property, you should return out of the function immediately.
The second return also ends the function, but as soon as it finds a name which doesn’t match. That return should only occur if all names don’t match. If the first in the loop isn’t a match, the others aren’t even checked.
This is also the issue with the third return.
You just need to reconsider how and where you put your if...else statements. A little tweaking should sort it.
EDIT: What he (@marcusparsons) said, far more succinctly than I did.