Looping Over Arrays

JavaScript ES2024 · ✓ verified by execution on 2026-08-12T17:51:58.799Z

Introduction

JavaScript provides several ways to loop through the elements of an array. The two most common and modern approaches are the array method forEach() and the language statement for...of. While they often achieve the same result, they work differently under the hood. Understanding these differences is crucial for writing clean, bug-free code, especially when you need to stop a loop early or perform asynchronous operations.

The forEach() method of Array instances executes a provided function once for each array element.

Iterating elements one by one
forEach() visits every element in order and returns nothing — the loop is run for its side effects, not for a result.

Basic forEach Example

The forEach() method is a higher-order function, meaning it takes another function (a callback) as an argument. It calls this provided function once for every item in the array. This approach is highly declarative—you tell JavaScript what to do for each item, rather than how to loop through them step-by-step.

javascript
const items = ['a', 'b'];
items.forEach(item => {
  console.log(item);
});
Output
a
b

Using for…of

While forEach is an array method, for...of is a standard looping construct built into the language itself. It works on any iterable object, not just arrays. This imperative style gives you more control over the loop’s execution flow, making it easier to read for complex logic and allowing you to pause or stop the loop at any time.

The for…of statement executes a loop that operates on a sequence of values sourced from an iterable object.

javascript
const items = ['x', 'y'];
for (const item of items) {
  console.log(item);
}
Output
x
y

Breaking Out of Loops

You can use break, continue, and return statements in a for…of loop.

javascript
const items = [1, 2, 3, 4];
for (const item of items) {
  if (item === 3) break;
  console.log(item);
}
Output
1
2

The break Misconception

There is no way to stop or break a forEach() loop other than by throwing an exception.

javascript
const items = [1, 2, 3];
try {
  items.forEach(item => {
    if (item === 2) break;
    console.log(item);
  });
} catch (e) {
  console.log(e.name);
}
This example raises an error (on purpose)
SyntaxError
SyntaxError

Accessing the Index

currentValue: The current element being processed in the array. index: The index of the current element.

Predict the output javascript

Read the code. What exactly will it print? Commit to an answer before you look.

const letters = ['a', 'b'];
letters.forEach((letter, index) => {
  console.log(index + ': ' + letter);
});
Output
0: a
1: b

Iteration Visualized

javascript · visualize
const arr = [];
arr[2] = 'c'; // sparse array
arr.forEach(x => console.log('forEach seen: ' + x));
for (const x of arr) console.log('for...of seen: ' + x);

Misconceptions

Edge Cases

Check yourself

Can you use a 'break' statement inside a forEach loop?

Reveal answer

No, forEach does not support break — The 'break' statement is not valid inside a forEach callback function. If you need to stop early, use a for...of loop instead.

What does the forEach method return?

Reveal answer

undefined — forEach always returns undefined. It is used solely for executing side effects, not for transforming arrays.

How do you access the current index inside a forEach loop?

Reveal answer

It is the second argument to the callback — The forEach callback receives the current value as the first argument, and the current index as the second argument.

Challenges

Challenge 1 +100 XP

Write a `for...of` loop that prints each name in the `guests` array.

javascript
  • Test 1 — expects "Alice\nBob\nCharlie"
Show solution (0 XP)
const guests = ['Alice', 'Bob', 'Charlie'];
for (const guest of guests) {
  console.log(guest);
}

🐞 Bug Hunt +100 XP

This code is supposed to log only the even numbers using `forEach`, but it throws a SyntaxError because it tries to use `continue`. Fix the code.

This code runs. It just does the wrong thing. Read it, find the defect, fix it — the tests below decide when you are right.

javascript
  • Test 1 — expects "2\n4"
Show solution (0 XP)
const numbers = [1, 2, 3, 4];
numbers.forEach(num => {
  if (num % 2 !== 0) {
    return;
  }
  console.log(num);
});