Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `return` keyword mean inside `forEach` function? [duplicate]

People also ask

What does return in forEach do?

The forEach method does not return a new array like other iterators such as filter , map and sort . Instead, the method returns undefined itself.

Does return break out of forEach?

return doesn't break a loop, the break does!

How do I return an item on forEach?

The forEach function doesn't return a the value you're expecting it to (docs here), which means that your isUniform function will always return true . For what you're trying to do, you could use an old-fashioned for loop, or use array. every(isTheSame) .

Can you return from forEach JS?

You can't make JavaScript's forEach() function return a custom value. Using return in a forEach() is equivalent to a continue in a conventional loop.


From the Mozilla Developer Network:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

  • A simple loop
  • A for...of loop
  • Array.prototype.every()
  • Array.prototype.some()
  • Array.prototype.find()
  • Array.prototype.findIndex()

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.


The return exits the current function, but the iterations keeps on, so you get the "next" item that skips the if and alerts the 4...

If you need to stop the looping, you should just use a plain for loop like so:

$('button').click(function () {
   var arr = [1, 2, 3, 4, 5];
   for(var i = 0; i < arr.length; i++) {
     var n = arr[i]; 
     if (n == 3) {
         break;
      }
      alert(n);
   })
})

You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp