Explain Codes LogoExplain Codes Logo

Go to "next" iteration in JavaScript forEach loop

javascript
promises
callbacks
best-practices
Anton ShumikhinbyAnton Shumikhin·Nov 4, 2024
TLDR

To skip an iteration in a forEach loop, use return; this behaves like continue in other loop types. Below is an example:

const nums = [1, 2, 3, 4, 5]; nums.forEach(num => { if (num % 2 === 0) return; // Even numbers detest the console console.log(num); // Only odd numbers show up: 1, 3, 5 });

The return statement stops the current callback for num % 2 === 0 (even numbers) and continues with the next iteration.

Interpreting return in a forEach loop

Within the forEach loop, return is a one-way ticket out of the current iteration. If some condition is fulfilled, return will allow you to ignore that specific iteration and continue with the rest. Because return ends execution, you don't need to add true; saying return; is enough to hop onto the next train.

Other Ways to Iterate

Employing for…of

for...of is a more power-packed loop structure that allows break, continue, and return with labels, making it a versatile choice when forEach starts to feel limited.

Crafting with Array.filter()

Pre-filter your array to focus on pertinent elements using Array.filter(). It’s like a custom clearance for your iterations.

Harnessing Array.map()

An Array.map() combined with a return statement can create a new array with applied transformations exclusively on complying elements, effectively leaving the others alone.

Smoother forEach with Best Practices

Handling Errors in forEach

Thrown errors in a forEach loop don't break the entire loop like in other loop types. This can result in unprevented bugs if not addressed.

Be Wary of Nested forEach Loops

In nested forEach loops, returning from an inner loop doesn't stop the outer one. Keeping this in mind saves from head-banging moment.

Performance Counts

forEach is not the performance champion when dealing with large datasets. Standard for loops or for...of offer better performance because they avoid additional function scopes with every iteration.