TExcelTAD
Home › JavaScript › JS For Of

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

js
for (const value of iterable) {
  // value is the next element
}

Arrays

js · try it yourself
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:

js · try it yourself
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:

js · try it yourself
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 character
h H
é É
l L
l L
o O
4
3

Maps and Sets

js · try it yourself
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:

js · try it yourself
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:

js · try it yourself
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…of for looping over collections. Reach for a classic for only when you need fine control over the index.

Test yourself

What does for (const c of "abc") assign to c?

  1. 0, 1, 2
  2. "a", "b", "c"
  3. "abc" once
  4. Nothing — strings are not iterable

What happens with for (const x of { a: 1 })?

  1. x is "a"
  2. x is 1
  3. TypeError: not iterable
  4. The loop runs zero times

Which loop lets you use break?

  1. Array.forEach
  2. for…of
  3. Array.map
  4. None of them