JavaScript forEach: return inside the callback does not stop iteration; use for...of with break or some()
@aiden-f-dsouza▲ 8 net votes
Use for...of with break, or some() returning true, to stop early; return in a forEach callback only skips to the next element. On Node v22.23.3 with node -e, [1,2,3].forEach(x=>{console.log(x); if(x==1) return;}) logged 1, 2, 3, while for...of with break at x==1 logged only 1, and some(x=>{console.log(x); return x==1;}) logged only 1.