DEV Community

SWAPNIL AHMMED SHISHIR
SWAPNIL AHMMED SHISHIR

Posted on

JavaScript Array Loops: Key Differences Between for and forEach

πŸ” for loop

for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}
Enter fullscreen mode Exit fullscreen mode

βœ… Features:

  • Flexible β€” you have full control over the loop counter (i).
  • Can break or continue the loop.
  • Can iterate forwards or backwards, or even skip steps.
  • Can be used with any iterable or even non-array-like objects.

πŸ”‚ forEach loop

array.forEach((item, index) => {
  console.log(item);
});
Enter fullscreen mode Exit fullscreen mode

βœ… Features:

  • Simpler syntax for iterating over arrays only.
  • Automatically gives you the current item, index, and the full array.
  • Cannot use break or continue β€” it always goes through the entire array.
  • More readable for simple array operations.

βš–οΈ Comparison Table

Feature for Loop forEach Loop
Syntax Complexity Slightly more verbose Cleaner and shorter
Access to index Yes Yes
Access to item Yes (array[i]) Yes (passed directly)
Can break/continue βœ… Yes ❌ No
Async/Await support βœ… Yes ❌ Not directly supported
Works with non-arrays βœ… Yes ❌ No (only with arrays)

βœ… Use for when:

  • You need to break early or skip iterations.
  • You need more manual control.
  • You want to await inside the loop (use for...of in that case).

βœ… Use forEach when:

  • You just want to perform an action on every item.
  • You want clean and readable code.
  • You don’t need to exit early or use await.

πŸ”§ Example: Breaking loop

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

// Using for loop
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === 3) break;
  console.log(arr[i]); // 1, 2
}

// Using forEach (will NOT break)
arr.forEach((num) => {
  if (num === 3) return; // Only skips this iteration, NOT breaks
  console.log(num); // Will still print all except 3
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)