Profile Lookup - can not figure out what is wrong

Can anyone tell me whats wrong in below code ? It works fine returns the result correctly in editor. But in freecodecamp environment it is failing all test cases.

// Only change code below this line
contacts.forEach(contact=>{
  if(contact.firstName == name){
      if(contact.hasOwnProperty(prop)) {
        console.log(`contact.firstName ${contact.firstName} ${contact[prop]}`);
         return contact[prop];
      } else {
          return "No such property";
      }
  } else {
      return "No such contact";
  }
});
// Only change code above this line
}```

In the future, please create your own topic when you have specific questions about your own challenge code. Only respond to another thread when you want to provide help to the original poster of the other thread or have follow up questions concerning other replies given to the original poster.

The easiest way to create a topic for help with your own solution is to click the Ask for Help button located on each challenge. This will automatically import your code in a readable format and pull in the challenge url while still allowing you to ask any question about the challenge or your code.

Thank you.

fthe return statement you have is from inside the forEach callback, your profileLookUp function doesn’t have a return statement

  1. You can’t return a value out of an forEach like that.

forEach

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

const names = ['Akira', 'John', 'Jill'];

function getNameForEach(nameToFind) {
  names.forEach(name => {
    if (name === nameToFind) {
      return name;
    }
  });
}

console.log(getNameForEach('John'));
// undefined

function getNameForEachWithReturn(nameToFind) {
  let returnName;
  names.forEach(name => {
    if (name === nameToFind) {
      returnName = name;
    }
  });
  return returnName;
}

console.log(getNameForEachWithReturn('John'));
// John
  1. You can’t return out of the loop and function on the first name that does not match because you have to check all the objects in the array.

For example:

lookUpProfile('Kristian', 'lastName');

First object:

{
  firstName: 'Akira',
  lastName: 'Laine',
  number: '0543236543',
  likes: ['Pizza', 'Coding', 'Brownie Points']
}

Your return logic:

if (contact.firstName == name) {
  if (contact.hasOwnProperty(prop)) {
    return contact[prop];
  } else {
    return 'No such property';
  }
} else {
  return 'No such contact';
}

As Akira is not the name Kristian you return out of the loop and function and never finish checking the rest of the objects for the name Kristian.