Profile Lookup Question [SOLVED]

So I’ve already solved the challenge, but I have a questions regarding challenge. So I have a better understanding of the logic that JS takes.

First: when the if conditional is setup correctly without the nested if conditional, but with the return statement for the value of the prop argument, and you add the else conditional after the if statement, why does the if statement end up false and JS moves to the else statement instead?

Ex:

for( var x = 0; x < contacts.length; ++x) {
if (contacts[x].firstName === firstName) {
return contacts[x][prop];
}
// the above statement will return true for the name and everything works except for the “No such contact/property” because we haven’t added the else conditional, but if you add the else conditional

else {
return “No such contact”;
}
// JS automatically switches to the else statement when the if conditional returns true if the function’s invoked arguments are within the object. Why is that?

Second: Why use the nested if conditional instead of the && since using the && logical operator will return true if you invoke the function with arguments that are present in the object, but JS still moves to the else statement instead.

Ex:

for( var x = 0; x < contacts.length; ++x) {
if (contacts[x].firstName === firstName && contacts[x].hasOwnProperty( prop)) {
return contacts[x][prop];
} else {
return “No such contact”;
}

// the above statement will return true if you invoke the function with arguments that exist in the object but JS still moves to the else conditional.

I can’t understand the logic, and would like an explanation so that when I encounter this same issue in the future and I’m asked why I can articulate it and have a clear understanding.

Thanks!

You are in a for loop so some of these records will not equal firstName. (same happens for the second case)

Use http://pythontutor.com/ to debug the code and you will see clearly.

  1. Adding the else changes the loop body to immediately return from the function whether the if condition is true or false - effectively the loop terminates on first iteration - without the else the loop continues to the next iteration if the if condition is false

thanks for the clarification! I get the logic now. I ran the test over with johnny bizel’s link to see the execution and after playing around with it, I saw the logic that you’re stated.

Thank you so much guys/gals! :slight_smile:

2: See https://forum.freecodecamp.org/t/nested-if-statements-and-composite-conditions/133780