When Not to Use the JavaScript forEach() Loop?

You should rethink about using the Array.prototype.forEach() loop in the following cases:

When You Need to return From the Loop

Using return within the callback of a forEach() loop does not stop the loop, instead it continues to the next element in the iteration. This happens because forEach() executes the callback function for each element of the array. To demonstrate this, let's look at the following example:

// ES5+
[ 1, 2, 3, 4 ].forEach(function (num) {
    if (num === 1) {
        return;
    }

    console.log(num);
});

// output: 2 3 4

As you can see from the example above, return does not halt the execution of the loop (as you may have expected), instead it stops the iteration when "num === 1" and continues to the next item. If you must use return inside a loop, then perhaps you should consider using an alternative.

When You Need to break Out of the Loop

There is no way to break out of a forEach() loop (except for when an exception is thrown). If you use the break keyword inside a forEach() loop, it would result in a SyntaxError. For example:

// ES5+
[ 1, 2, 3, 4 ].forEach(function (num) {
    if (num === 1) {
        // Error: Uncaught SyntaxError: Illegal break statement
        break;
    }

    console.log(num);
});

Although an exception would stop a forEach() loop, you should not throw an exception for the sole purpose of breaking out of a forEach loop. If you run into such a situation, then you probably need to rethink your design and use something else.

When You Need to Use continue in the Loop

There is no way to use continue in the callback of a forEach() loop. If you use the continue keyword, it would result in a SyntaxError. For example:

// ES5+
[ 1, 2, 3, 4 ].forEach(function (num) {
    if (num === 1) {
        // Error: Uncaught SyntaxError: Illegal continue statement:
        // no surrounding iteration statement
        continue;
    }

    console.log(num);
});

Even though using return inside the callback of a forEach() loop would halt execution for the current iteration and move on to the next item in the loop, you should not use it to mimic the functionality of continue. If you run into such a situation, then you probably need to choose an alternative.

When You Need to Use async/await Inside the Loop

The forEach() loop expects a synchronous function as a callback. This means that it does not wait for promises. To demonstrate this, let's look at the following example:

// ES5+
const sleep = function () {
    return new Promise(function (resolve) {
        setTimeout(resolve, 50);
    });
};

console.log('Start');

[ 1, 2, 3, 4 ].forEach(async function (num) {
    await sleep();
    console.log(num);
});

console.log('End');

// output: 'Start' 'End' 1 2 3 4

As you can see from the example above, await does not work inside the callback of forEach() loop. This is so by design. If you have a need to use async/await inside a loop, then it's probably a good idea to use alternatives.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.