Categories
JavaScript Answers

How to short circuit Array.forEach like calling break with JavaScript?

Spread the love

To short circuit Array.forEach like calling break with JavaScript, we use a for-of loop.

For instance, we write

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (const el of arr) {
  console.log(el);
  if (el === 5) {
    break;
  }
}

to use a for-of loop to loop through the arr array.

And we use break to stop the loop when el is 5.

el is the element we’re looping through.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *