The Right Way to Break from forEach in JavaScript

The Right Way to Break from forEach in JavaScript

And other alternatives
Ferenc Almasi β€’ 2022 November 04 β€’ Read time 4 min read
Learn what are some workarounds and alternatives to break and return values from a forEach loop in JavaScript
  • twitter
  • facebook
JavaScript

How can you break and return from a forEach loop in JavaScript? The short answer is: you can't.  Breaking from forEach loops in JavaScript is not possible. However, there are some workarounds, and there are also alternatives.

While we cannot break and return from a forEach in JavaScript, we can still return values with an external variable in the following way:

Copied to clipboard! Playground
let productDetails

products.forEach(product => {
    if (product.id === 123) {
        productDetails = product 
    }
})
forEach.js
Workaround for returning value from a forEach

Here we essentially set a variable outside of the forEach loop to one of the items, based on an ID. Given the right condition inside an if statement, we can grab and "return" the correct value. However, this can be rewritten in better ways. Here are five different alternatives you can use when you need to break from a forEach.


Using Array.find

The above example can be also rewritten with the find method. As the name suggests, the find method is used for finding a specific element in an array. It returns one item that first passes the test in the callback function. For example:

Copied to clipboard! Playground
// This will return the product with the ID of 1
products.find(product => product.id === 1)

// Even though we might have multiple products which are on sale
// this will only return the first match
products.find(product => product.onSale)

// This will return undefined
products.find(product => product.id === 'invalid')
find.js
Returns the item given a predicate

For the first example, we have one object returned as each ID is unique. But in the second one, we might have multiple products that are on sale, but we still get back only the first one that passes the test. If there is no match, the find method simply returns undefined.


Using Array.findIndex

A similar but slightly different solution to find is using the findIndex method. In case you need to return the index of the element inside an array, you can use the findIndex method. This will return the index of the element if found. If no element is found with a predicate, it will return -1.

Copied to clipboard! Playground
// This will return 2
[1, 2, 3].findIndex(number => number === 3)

// This will return -1
[1, 2, 3].findIndex(number => number === 4)
findIndex.js
Returns the index of the item, or -1 if no item is found
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Using Array.some for Returning True or False

In case you need to break from a loop and return a boolean, we can use the some method. Unlike find where we expect an item to be returned from the array, some returns either a true or false. If at least one item in the array matches the criteria, this method will instantly return true. Take the following as an example.

Copied to clipboard! Playground
// We do have some products which are on sale so we get back true
products.some(product => product.onSale)

// None of the items are less than 0, so we get back false
[1, 2, 3].some(item => item < 0)

some.js
Returns either true or false if at least one item passes the predicate

In the first example, we get back true as we are only interested in whether there is at least one item on sale. Likewise, in the second example, we are only interested in whether at least one item is below 0. Since none of them are below 0, the method returns false.


Using Array.every for Checking Every Element

every is very similar to some in terms of the value returned: either return a true or false. But instead of checking if a single item passes the predicate, it will only return true if all items pass the test. Let's have a look at an example.

Copied to clipboard! Playground
// This produces false
products.every(product => product.onSale)

// This produces true
products.every(product => product.name)
every.js
Returns true if all items pass the predicate. Otherwise returns false

In the first example, we get back false as possibly not every product is on sale. However, we can check if every product has a name, in which case every would produce a true value.


Using Regular Loops

Last but not least, we can also use regular loops which support the break and continue statements. In the below example, we use a regular for, a for...of, and while loop to demonstrate how to break when a statement is true.

Copied to clipboard! Playground
const array = [1, 2, 3]

// Using a for loop
for (let i = 0; i < array.length; i++) {
    if (array[i] === 2) {
        break
    }

    console.log(array[i])
}

// Using a for...of loop
for (const item of array) {
    if (item === 2) {
        break
    }

    console.log(item)
}

// Using a while loop
let i = 0

while (i < array.length) {
    if (array[i] === 3) {
        break
    }

    console.log(i)
    i++
}
Using a for, for...of and while loop for breaking

If you would like to learn more about other array methods too, such as map, filter or reduce, make sure you check out our article below.

How to Open Any File in Javascript with Progressbar
  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.