Why won't this code work?

I’m on the Basic JavaScript: Profile Lookup exercise and I’m wondering why this code won’t work.

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

return “No such contact”;
}

This is the correct code:

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


I thought I could combine the two if statements by using && (AND) but when I try this, it doesn't work and I can't figure out why.

This logic will return “No such property” if contacts[i].firstName is not the same as name. The logic of this loop will only check the first item in contacts because it always returns something in the loop.

You can think all possibilities like a tree diagram. Let’s check here the possibilities to see the difference;
Correct Code:
First condition True & Second Condition True => contacts[i][prop]
First condition True & Second Condition False => No such property
First condition False & Second Condition True=> No such contact
First condition False & Second Condition False => No such contact

Your Code:
First condition True & Second Condition True => contacts[i][prop]
First condition True & Second Condition False => No such property
First condition False & Second Condition True=> No such property
First condition False & Second Condition False => No such property

  • will never reach "return “No such contact” line, because when the code reaches a “return”, the function is stopped.

check here: Return

Thanks a lot. I now understand why my logic was flawed.