1

Can somebody please tell me why this code works perfectly fine:

function getImage(images, path){
  path = path.slice(0, path.lastIndexOf("/"));

  let res;

  images.forEach(img => {

    let imgPath = img.node.absolutePath.slice(0, img.node.absolutePath.lastIndexOf("/"))

    if (imgPath === path){
      console.log(img.node)
      res = img.node;
    }
  });

  return res;

}

It returns the correct img.node object that I am looking for.

If I replace the "res = img.node" with "return img.node", it will always tell me the value is undefined.

Lorenz Killer
  • 95
  • 1
  • 6
  • 6
    You can't `return` from within the `forEach` callback function. – Andy Nov 08 '18 at 19:24
  • 1
    And even if you could a return in an inner function call doesn't return to the outer function – charlietfl Nov 08 '18 at 19:26
  • 3
    As @Andy said, the `return` statement only returns from the callback for that iteration of the `forEach` (which does nothing), it doesn't return from the outer function. In order to return from the outer function, you can use a standard `for` loop with a return statement, or you can use something like `return images.find(img => ...).node` – mhodges Nov 08 '18 at 19:26

0 Answers0