Dear JavaScript Aficionado,

If I must answer you quickly how to use the “continue” directive in a forEach method, then the short answer is: You can’t, and you don’t need to do it.

Why?

Because the forEach method of an array isn’t considered a traditional loop, so “continue” and “break” don’t affect its execution.

In case you need to skip the execution of some code when specific criteria are met, then you must use “return” like this:

const arr = [1, 2, 3, 4, 5, 6, 7];

//Correct 
arr.forEach((element, index) => {
    if (index === 3) {
        return;
    }

    //Some code that will be skipped for element with index 3
    process(element);
});

//Wrong
arr.forEach((element, index) => {
    if (index === 3) {
        continue; //Won't do anything;
    }

    //This won't be skipped
    process(element);
});

//Wrong
arr.forEach((element, index) => {
    if (index === 3) {
        break; //Won't do anything;
    }

    //This won't be skipped
    process(element);
});

Because forEach is a method (a function that belongs to an object) that invokes a callback, the latter can be interrupted by returning a value (in our example, it’s “undefined”).

Many people get confused about this because they focus on the word “for” in the method’s name and somehow overlook the word “each.” By focusing on the former, they quickly associate it with the well-known “for” loop.

But if we include the word “each,” it becomes pretty clear what it does – it ALWAYS iterates over every element of an array. Even if you use “return” to skip some code execution in the callback function, the array element still needs to be visited.

So if you deal with big arrays and you have to think about optimizing stuff like the “time complexity” of your code, then you will need to use a traditional “for-of” loop because it will allow you to “continue” and/or “break” and thus – don’t visit elements unnecessary.

I hope this short discussion was helpful to you!

Be Happy,

Sashe

P.S. If you would like to read and discover more advanced tips, techniques, and strategies, check out this link (I think you’ll like what’s on the other side).