JavaScript For Of
The for…of loop goes through the values of an iterable — arrays, strings, Maps, Sets, NodeLists, generator results and more. It's the cleanest way to say "do this for each item".
Syntax
for (const value of iterable) {
// value is the next element
}Arrays
const languages = ["JavaScript", "Python", "Rust"];
for (const lang of languages) {
console.log(`I like ${lang}`);
}I like JavaScript
I like Python
I like Rust
Use const for the loop variable unless you reassign it inside the body — each iteration gets a fresh binding.
Index and value together
Arrays have an entries() method that yields [index, value] pairs. Combine it with destructuring:
const podium = ["Ana", "Bo", "Cy"];
for (const [i, name] of podium.entries()) {
console.log(`#${i + 1}: ${name}`);
}#1: Ana
#2: Bo
#3: Cy
Strings
A string is iterable too, character by character. Unlike indexing with str[i], for…of correctly handles characters outside the basic plane, such as emoji:
const word = "héllo";
for (const ch of word) {
console.log(ch, ch.toUpperCase());
}
const party = "hi🎉";
console.log(party.length); // 🎉 is two UTF-16 code units
console.log([...party].length); // but one characterh H
é É
l L
l L
o O
4
3
Maps and Sets
const stock = new Map([
["apples", 10],
["pears", 4],
]);
for (const [fruit, count] of stock) {
console.log(fruit, count);
}
const unique = new Set(["red", "blue", "red", "green"]);
for (const color of unique) {
console.log(color);
}apples 10
pears 4
red
blue
green
Objects are not iterable
Plain objects can't be used directly with for…of. Loop over Object.keys(), Object.values() or Object.entries() instead:
const scores = { math: 91, art: 78, music: 85 };
try {
for (const s of scores) console.log(s);
} catch (err) {
console.log(err.message);
}
for (const [subject, score] of Object.entries(scores)) {
console.log(subject.padEnd(6), score);
}scores is not iterable
math 91
art 78
music 85
for…of vs forEach
Both visit every element, but for…of is a real loop, so you can break, continue, return from the enclosing function and await inside it:
const numbers = [3, 8, 15, 4, 23];
for (const n of numbers) {
if (n % 2 === 0) continue; // skip even numbers
if (n > 20) break; // stop entirely
console.log(n);
}3
15
for…of |
arr.forEach(fn) |
for…in |
|
|---|---|---|---|
| Gives you | values | values (+ index) | keys |
| Works on | any iterable | arrays (and NodeList, Map, Set) | objects |
break / continue |
✅ | ❌ | ✅ |
await inside |
✅ | ❌ (doesn't wait) | ✅ |
Tip: Default to
for…offor looping over collections. Reach for a classicforonly when you need fine control over the index.
Test yourself
What does for (const c of "abc") assign to c?
- 0, 1, 2
- "a", "b", "c"
- "abc" once
- Nothing — strings are not iterable
What happens with for (const x of { a: 1 })?
- x is "a"
- x is 1
- TypeError: not iterable
- The loop runs zero times
Which loop lets you use break?
- Array.forEach
- for…of
- Array.map
- None of them