What are the differences between these two functions?

What are the differences between these two functions?
0

#1

Hi there!
I was working on the profile lookup challenge (I will post the solution, don’t read if you haven’t completed it!).

I have two versions of the function, one works and one doesn’t, the only difference is in the order of the else statement “return no such contact”. I do not understand what is the difference between them.

This is the correct one:

function lookUpProfile(firstName, prop){
// Only change code below this line
for (i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === firstName) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return “No such property”;
}
}
} return “No such contact”;

// Only change code above this line
}

This does not work:

function lookUpProfile(firstName, prop){
// Only change code below this line
for (i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === firstName) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return “No such property”;
}
} else {
return “No such contact”;
}
}
// Only change code above this line
}


#2

Cause in first case u check whole contacts with ur desired name and only then when loop end
by no one with same name found

return 'no such contact' occurs

But if something success in loop by meanimg returning control ( value ) to caller then line
return ‘no such contact’ will not happen

P.s
Just trace brackets


#3

In the second case return 'no such contact' is inside the loop but should only be reached if the first conditional if (contacts[i].firstName === firstName) is not met. Then why is that wrong? Does being inside a loop affect it somehow?


#4

Even so, inside the for-loop, all “paths” will lead to a return, effectively breaking your loop.


#5

Oh! I get it now! Thank you @nameToReachPeople @kevcomedia ! You were very helpful.