Profile Lookup forEach - solved

Following code should work. It seems that it does not work with forEach function. It works fine with for loop function.

function lookUpProfile(firstName, prop){
    // Only change code below this line
    var firstNameFound = false;  
    var propFound = false;
    contacts.forEach(function(obj) {
        if (obj.firstName === firstName) {
           firstNameFound = true;
           if (obj.hasOwnProperty(prop)) {
               console.log(firstName);
               console.log(prop);
               console.log(obj[prop]);
               propFound = true;
               return obj[prop];
          }
     }
  });
  if (propFound === false) {
      if (firstNameFound === false) return 'No such contact';
          return 'No such property';
  }
  throw 'oops';
  // Only change code above this line
}

This is your bug.

This return returns from .forEach() and not from main function. And as forEach has no return value, you are basically throwing it away.

3 Likes

Thanks jenovs. Yup, my mistake.

It seems that you cannot break out of forEach with return or any other way.