I amm new to javascript and am working through freecodecamp's resources (amongst other things). There was a challenge task to loop through phone contacts and I am sure some people will be familiar with it. I managed the task just fine, but am confused as to why the final return statement needs to exist outside the for loop, as opposed to an else statement for the outer if.
function lookUpProfile(name, prop){
for (var i = 0; i < contacts.length; i++) {
if (name === contacts[i].firstName) {
if (prop === "lastName" || prop === "number" || prop === "likes") {
return contacts[i][prop];
}else{
return "No such property"
};
}
}
return "No such contact";
};
If I ever nested the final return statement (as an else) inside the for loop, the code would appear to go straight to this, even though the conditions for the initial if statement were true.
Can anyone please explain why? If you need any further information please let me know. I have tried searching google for why this might be the case but I haven't managed to find anything.
Thanks!
forloop it will returnNo such contactifname === contacts[1].firstName. You have to look through all of the items to make sure that the one you are looking for is not among them.propisn't one of those three values? I can't make out what the logic is meant to be. Also, ifprophas a known set of three values, why not check it before even starting the loop?returninside the for loop, the function would exit when hitting the first non-match. The function would never find anybody unless they happen to be first in the list.