0

Is it possible to exit a (native) function from inside the callback that that function takes?

For example, I only want the first callback, that logs 1, to execute.

a = [1, 2, 3];

a.forEach(function (element) {
    console.log(element);
    return; 
});
tonitone120
  • 1,920
  • 3
  • 8
  • 25

2 Answers2

3

Depends on the function. In the specific case of forEach the answer is no. This is explained on the documentation:

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 for loop
  • A for...of / for...in loops
  • Array.prototype.every()
  • Array.prototype.some()
  • Array.prototype.find()
  • Array.prototype.findIndex()

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.

ariel
  • 15,620
  • 12
  • 61
  • 73
0

If you need to do it using forEach() you could check element against a target number (in this case, x) and if it meets the condition, quit the loop rather than execute.

a = [1, 2, 3];
x = 1; // target number

a.forEach(function(element) {
  if (element > x) { // check if element is greater than the target number
    return; // if so, exit the function
  }
  console.log(element);
  return;
});
freginold
  • 3,946
  • 3
  • 13
  • 28