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!