The Right Way to Break from forEach in 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:
let productDetails
products.forEach(product => {
if (product.id === 123) {
productDetails = product
}
})
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:
// 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')
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.
// This will return 2
[1, 2, 3].findIndex(number => number === 3)
// This will return -1
[1, 2, 3].findIndex(number => number === 4)
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.
// 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)
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.
// This produces false
products.every(product => product.onSale)
// This produces true
products.every(product => product.name)
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
.
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++
}
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.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: