JavaScript by Patrik

Use every() instead of forEach()

The every() function behaves exactly like forEach(), except it stops iterating through the array whenever the callback function returns a false value.

// Prints "1, 2, 3"
[1, 2, 3, 4, 5].every(v => {
  if (v > 3) {
    return false;
  }

  console.log(v);
  // Make sure you return true. If you don't return a value, `every()` will stop.
  return true;
});

With every(), return false is equivalent to a break, and return true is equivalent to a continue.

Another alternative is to use the find() function, which is similar but just flips the boolean values. With find(), return true is equivalent to break, and return false is equivalent to continue.

Comments

Leave a Comment

All fields are required. Your email address will not be published.