please help , my code wont iterate through the whole contacts list
function lookUpProfile(name, prop){
for (var i = 0; i < contacts.length; i++) {
if(contacts[i]["firstName"] === name && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
}else if(contacts[i]["firstName"] !== name) {
return "No such contact";
}else if(contacts[i].hasOwnProperty(prop) === false) {
return "No such property"
}
}
}
lookUpProfile("Akira", "lastName");
No worries, this is a common error that usually takes practice to “read”.
In pseudo-code this is what your code is instructed to do, I’m talking about the first version: the return one
Loop on every element
if element x firstName is name and element x has property
Stop and return element x property
if element x firstName is not name
Stop and return "No such .."
if element x don't have prop
Stop and return "No such.."
Do you see the error?
Or in other word, how can I stop at the first element and tells “We don’t have it” if we haven’t checked them all first?
function lookUpProfile(name, prop){
for (var i = 0; i < contacts.length; i++) {
if(contacts[i]["firstName"] === name) {
if(!contacts[i].hasOwnProperty(prop) ){
return "No such property";
}else
return contacts[i][prop];
}
}
return "No such contact";
}