In this case, how come the last return statement doesn't get execute when IF is true?

Hello,
Please see below.
The last return statement is outside of IF. How come that last return statement doesn’t get executed when the first IF is true?

That last return statement “No such contact” is outside of the first IF. Shouldn’t that last return statement be executed no matter what?

function lookUpProfile(name, prop) {
  for (var x = 0; x < contacts.length; x++) {
    if (contacts[x].firstName === name) {
      if (contacts[x].hasOwnProperty(prop)) {
        return contacts[x][prop];
      } else {
        return "No such property";
      }
    }
  }
  return "No such contact";
}

Hello~!

return ends a function. When your first if statement is true, the function enters the loop. When the second if statement is true, you hit the if/else block, which either returns the property or “No such property”. That final return only hits when the loop has iterated through the entire contacts object and not found the name.

1 Like