Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript for...of Loop

The for...of loop iterates over values in arrays and other iterables.

It is clean, readable, and avoids manual indexing.

Why We Need It

Most of the time you care about values, not indexes. for...of keeps that intent clear.

It also works with strings, maps, and sets, so it is versatile.

Syntax

for (const value of iterable) { ... }

Basic Example

1. Array values

const items = ["a", "b", "c"];

for (const item of items) {
  console.log(item);
}

for...of iterates values directly.

Real World Example

2. String characters

const word = "code";

for (const char of word) {
  console.log(char);
}

Each iteration yields one character.

Multiple Use Cases

Iterate Values

for...of iterates over values from arrays, strings, maps, sets, and other iterables.

It is the most readable way to loop over arrays when you only need values.

Works with Strings

for...of can iterate over string characters one by one.

This is useful for parsing and validation.

Breaking and Continuing

You can use break and continue inside for...of loops.

This gives you full control over the iteration.

More Examples

3. Map values

const map = new Map([["a", 1], ["b", 2]]);

for (const [key, value] of map) {
  console.log(key, value);
}

for...of works with Maps and Sets.

4. Break early

const nums = [1, 2, 3, 4];

for (const n of nums) {
  if (n === 3) break;
  console.log(n);
}

Use break to exit early.

Comparison

Without

const items = ["a", "b"];
for (let i = 0; i < items.length; i++) {
  console.log(items[i]);
}

With

const items = ["a", "b"];
for (const item of items) {
  console.log(item);
}

Common Mistakes and Fixes

Using for...of on objects

Objects are not iterable; use Object.keys or for...in instead.

Needing index but using for...of

Use entries() or a classic for loop for indices.

Mutating array while iterating

Be careful when adding or removing items during the loop.

Interview Questions

What does for...of iterate?

Values from any iterable like arrays or strings.

How do you get index with for...of?

Use array.entries() and destructure index and value.

Why choose for...of over for?

It is more readable when you only need values.

Practice Problem

Practice: Loop through an array of names and print each one.

const names = ["Ava", "Lee", "Ravi"];
// TODO: print each name

One Possible Solution

const names = ["Ava", "Lee", "Ravi"];
for (const name of names) {
  console.log(name);
}

Frequently Asked Questions

What can for...of iterate?

Any iterable: arrays, strings, maps, sets, and more.

How do I get the index?

Use array.entries() or a traditional for loop.

Can I use break and continue?

Yes, just like other loops.

Try It Yourself

Try iterating different arrays and strings with for...of.