exit foreach loop js

Exit foreach loop in JavaScript

Looping is an essential part of programming, and JavaScript provides several loop types to iterate through objects and arrays. The for each loop is one of them, which loops through each element of an array or an iterable object until the end or until a break statement is executed. However, sometimes you may want to exit the loop prematurely without completing all iterations based on certain conditions. This can be achieved using the break statement.

Syntax:


array.forEach(function(currentValue, index, arr), thisValue)
{
    // code to be executed for each element
    if (condition) {
        break;
    }
}

The forEach() method takes a callback function as an argument that is executed for each array element. The function can take up to three parameters: the current element value, the current element index, and the array itself. Additionally, you can pass a second argument to set the value of this inside the function. To exit the loop when a condition is met, you can use the break keyword inside the function block.

Example:


const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(num) {
    console.log(num);
    if (num === 3) {
        break;
    }
});

// Output: 
// 1
// 2
// 3

In this example, we create an array of numbers and iterate over it using the forEach() method. Inside the callback function, we log each element to the console and check if the current value is equal to 3. If it is true, we break out of the loop, and the remaining elements are not processed.

Another way to exit a for each loop is by returning false from the callback function. This will stop the iteration and exit the loop. However, this approach only works for the every() and some() array methods, not for the forEach() method.

In conclusion, the break statement is the best way to exit a for each loop in JavaScript. It allows you to terminate the iteration based on specific conditions and provides more flexibility than other approaches.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe