Profile Lookup - final return statement

Working through this challenge and with the help of the forum was able to complete. My one question in regards to this Profile Lookup code is with the final return “No such contact”;

-why is this return outside of the ‘for’ loops curvy brackets?
-could you place it one tier/nest up so it would be outside of the first ‘if’ statements brackets? To me this would make more sense as it is returning “No such contact” if the first ‘if’ statement is false. (example below directly below is not correct per codecamp run test; furthest down example is correct)

for (var 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”;
}

Your code so far

//Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    }
];


function lookUpProfile(firstName, prop){
// Only change code below this line
for (var 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
}

// Change these values to test your function
lookUpProfile("Owen", "likes");

If you moved that statement it would not work as expected. Anything inside your for loop is only checking one record so if the first record was not a match then your function would return ‘no such contact’ and quit.

Your for loop handles these cases
contact found/property found
contact found/ property not found

The only other choice if neither of above or true would be
contact not found

So after exhausting all other possibilities if no test has triggered your return yet then “No such contact” is returned as the only remaining possibility.

1 Like

Perfect response. Thank you for the clarification.