Also please always include all of your code. Maybe not the given data, like the contacts list, but the complete function, just in case.
Anyway, when you return in a function, you leave the function. Period. It is over. The function is done. So, in your code inside the loop:
if (name === contacts[i].firstName){
if (contacts[i].hasOwnProperty(prop)){
return contacts[i].prop;
} else {
return 'No such property';
}
} else {
return 'No such contact';
}
Every single path has a return in it. So, it will never test anything except the first element.
If that is the case, it should still work if it is the first contact. So, I test it with this:
console.log(lookUpProfile("Akira", "number"))
I like to put in log statements if I don’t understand something. So, I do this:
function lookUpProfile(name, prop) {
console.log('entering function name =', name, ' and prop =', prop)
for( let i=0 ; i < contacts.length ; i++ ) {
console.log('\ni =', i)
console.log('this contact', contacts[i])
if (name === contacts[i].firstName){
console.log('name found')
console.log('has property?', contacts[i].hasOwnProperty(prop))
if (contacts[i].hasOwnProperty(prop)){
console.log('property found')
return contacts[i].prop;
} else {
console.log('property not found')
return 'No such property';
}
} else {
console.log('contact not found')
return 'No such contact';
}
}
}
I see that everything seems to work fine for that first thing in the collection. Why is it returning undefined
. Then I notice this line:
return contacts[i].prop;
prop is a variable containing a string, the property we want. Is that how you access a property if the name is in a string?
When I fix that, it can at least look up information for the first contact in the list. Now you’ve got to figure out how to keep it from quitting too early. I was able to get it to work by rearranging a little bit of your logic. You have the right idea, it’s just that something is being done at the wrong time. You’re almost there.