Member-only story

Will return exit the loop in forEach

Beck Moulton
3 min readSep 8, 2023

--

Using a return statement within a forEach loop in JavaScript does not exit or terminate the loop; instead, the forEach loop continues to execute all remaining iterations. The return statement within a forEach loop only returns from the current iteration callback function, not from the entire loop. For example:

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

array.forEach(num => {
if (num === 3) {
return;
}

console.log(num);
});

// Output:
// 1
// 2
// 4
// 5

When num equals 3, the return statement only returns from the current iteration's callback function, while the forEach loop continues execution, resulting in the output of 4 and 5.

There are specific loop constructs in JavaScript where a return statement can exit or break the entire loop execution.

for Loop:

In a for loop, a return statement will completely exit the loop and interrupt all subsequent iterations:

for (let i = 0; i < 5; i++) {
if (i === 3) {
return;
}
console.log(i);
}
// Output: 0 1 2

for...in Loop:

A return statement will also immediately exit a for...in loop:

for (let i in obj) {
if (i === 'foo') {
return;
}
// ...
}

for...of Loop:

A return statement can break out of a for...of loop:

for (let x of array) {
if (x === 'bar') { return; }
// ...
}

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet