We can use Array.some() method to create a short circuit Array.forEach Like Calling Break. The Array.forEach() loop is a built-in method in JavaScript that is used to reiterate over any array and execute a function for each element of the array.
The Array.forEach() method is used to execute a provided function once for each element in an array. However, it does not provide a built-in mechanism to break or exit the loop prematurely like the break statement in a traditional for loop.
1. Using Array.some() Method
The Array.some() method can be used to iterate over an array and return true as soon as the condition is met, thereby short-circuiting the loop. If the condition is not met for any element, the loop continues until all elements have been processed.
Syntax
array.some(callback(element[, index[, array]])[, thisArg])const array = [2, 4, 8, 10];
let found = false;
array.some(function (element) {
if (element === 6) {
found = true;
return true; // Short-circuits the loop
}
});
console.log("Output: ", found); // false
Output
Output: false
2. Using for...of loop
Another way to short-circuit an array loop is to use a for...of loop instead of Array.forEach(). A for...of loop provides a built-in mechanism to break or exit the loop prematurely using the break statement.
Syntax
for (variable of iterable) {
// code to be executed
}const array = [9, 4, 3, 11, 10];
let isFound = false;
for (const element of array) {
if (element === 3) {
isFound = true;
break; // short-circuits the loop
}
}
console.log("Output: ", isFound); // true
Output
Output: true
3. Using Array.every() Method
Similar to Array.some(), the Array.every() method can also be used to iterate over an array and return false as soon as the condition is not met, thereby short-circuiting the loop. If the condition is met for all elements, the loop continues until all elements have been processed.
Syntax
array.every(callback(element[, index[, array]])[, thisArg])const array = [11, 12, 13, 14, 51];
let isOdd = true;
array.every(function (el) {
if (el % 2 === 0) {
isOdd = false;
return false; // short-circuits the loop
}
return true;
});
console.log("Output: ", isOdd); // false
Output
Output: false