3 things to know about forEach() in JS

Neetish Raj
2 min readFeb 21, 2022

--

If we are using the convenient Array.forEach() over the traditional for loop in JS then we should be aware of these 3 points.

  1. ‘break’ and ‘continue’ are SyntaxError inside forEach.
  2. ‘return’ behaves like ‘continue’.
  3. forEach() doesn’t mutate the array but it’s possible by referencing the original array.

1. ‘break’ and ‘continue’ are Syntax Error

So, in a simple for-loop, you can always do “break” or “continue” but not inside forEach’s callback. Both break and continue are uncaught syntax errors inside forEach’s callback.

const arr = [1, 2, 3, 4, 5];arr.forEach((item, index, arrRef) => {
if(item === 3) break;
});
// SyntaxError: Illegal break satement

The same goes for ‘continue’ 👇. It says no surrounding iteration statement, as it doesn’t detect forEach’s callback as an iteration statement.

const arr = [1, 2, 3, 4, 5];arr.forEach((item, index, arrRef) => {
if(item === 3) continue;
});
// SyntaxError: Illegal continue satement: no surrounding iteration statement

2. ‘return’ behaves like ‘continue’

‘return’, doesn’t throw any syntax error but it just behaves like ‘continue’. So technically, ‘continue’ is possible in forEach loop.

const arr = [1, 2, 3, 4, 5];const ret = arr.forEach((item, index, arrRef) => {
if(item === 3) return 3;

console.log(item);
});
// Output
1
2
4
5

The important thing to note is that forEach never returns any value after iterations, so in the above example value of ‘ret’ will be undefined.

3. forEach() doesn’t mutate Array but it’s possible.

const arr = [1, 2, 3, 4, 5];const ret = arr.forEach((item, index, arrRef) => {
item *= 2;
});
console.log(arr); // [1, 2, 3, 4, 5]

Now, if we want to mutate ‘arr’ within forEach’s callback then we have to use the actual ‘arr’ reference provided by 3rd argument in the callback.

const arr = [1, 2, 3, 4, 5];const ret = arr.forEach((item, index, arrRef) => {
arrRef[index] = arrRef[index] * 2;
});
console.log(arr); // [2, 4, 6, 8, 10]

Conclusion

  • forEach is intentionally flawed in its behavior when compared with other looping alternatives like for and for-of.
  • forEach()’s use-case is that it’s just a more readable, non-stopping looping mechanism that prevents us from doing any indexing errors.
  • Mutating an Array while iterating over it using forEach is never recommended. That’s just not the use case of forEach().

Reference

--

--

Neetish Raj

Full stack Development | Product Engineering | Recruitment