Profile Lookup (JavaScript Challenege/Exercise) - Code explanation

Your for loop version has the exact same problem your while loop had without the break statements. It will always show the very last value of result (which in this case is “No such contact”).

Below, I have re-written your for loop solution, so you can see how you would do it with as little code changed as possible:

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

FYI - In the future, please see (Forum Code Formatting) under Code Blocks for how to format your code when posting. It really helps those of us who want to help to not have to reformat it on our own to begin to assist.

2 Likes