Finders Keepers - return inside forEach

Tell us what’s happening:

Why it is not possible to do a break or return inside of a forEach-loop like in a for-loop?

Your code so far


function findElement(arr, func) {
  let num = undefined;
  arr.forEach(n => {
    if(func(n)) return n;
    //does nothing
  });
  return num;
}

console.log( 
findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })
)
   

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers

It’s not that it does nothing. it is returning from the inner function.

What @snowmonkey said, but more generally you can throw to break out of a forEach, but that’s it: it’s designed to always iterate through each value. Use a loop if you want to break (as you do in this case, where you want to either assign to num then stop looping, or get rid of num frpm your code and just return the value once it’s found)

1 Like