JavaScript for...of and for...in Loops: Iterating Arrays, Strings, Maps and Object Keys
for...of (values of arrays, strings, Maps, Sets, generators) vs for...in (enumerable keys, inherited ones included): indexes with entries(), objects with Object.entries, key order, holes, changing collections mid-loop, early exit and cleanup, and for await.
kvi5hnuCode Sprout team member7 min readOn this page
The classic for loop (article 41) works through positions: you manage an index and read arr[i]. Most of the time you don't care about positions; you want each value. That's what for...of does, and it works on far more than arrays. Its older lookalike, for...in, does something quite different: it walks through an object's property names. Mixing them up is one of the most common JavaScript mistakes, so this article covers both side by side.

for...of: the values of an iterable
for (const value of iterable) statement
for...of (ES2015) asks the object for an iterator and runs the body once for each value it produces. Arrays, strings, Map, Set, typed arrays, arguments, DOM collections like NodeList, and generators are all iterable (part 12 explains the protocol).
const total = [];
for (const price of [3, 4, 5]) total.push(price * 2);
console.log(total);
const chars = [];
for (const ch of "héy👋") chars.push(ch); // by code point, emoji intact
console.log(chars);
for (const [key, value] of new Map([["theme", "dark"], ["lang", "pt"]])) {
console.log(key, "=", value);
}
const unique = [];
for (const n of new Set([3, 3, 4])) unique.push(n);
console.log(unique);
[ 6, 8, 10 ]
[ 'h', 'é', 'y', '👋' ]
theme = dark
lang = pt
[ 3, 4 ]
Notes:
- Use
constfor the loop variable: each iteration gets a new binding, soconstworks (unlike in a classicforheader) and prevents accidental reassignment. Useletonly if you reassign it in the body. - The loop variable can be a destructuring pattern (article 28), which is how the Map example gets
keyandvalue. - Strings are iterated by code point, not by UTF-16 code unit, so emoji and other characters outside the BMP stay whole (article 14). Characters built from several code points, like some flags and family emoji, still come out in pieces;
Intl.Segmenterhandles those (part 11).
Getting the index too
for...of gives values only. When you need the index, iterate over entries(), which produces [index, value] pairs:
const podium = ["Ana", "Bea", "Cai"];
for (const [i, name] of podium.entries()) {
console.log(`${i + 1}. ${name}`);
}
1. Ana
2. Bea
3. Cai
Plain objects aren't iterable
A plain object has no iterator, so for...of on it throws a TypeError. Choose what you want to iterate and ask for it explicitly:
const stock = { apples: 4, pears: 0 };
try {
for (const item of stock) {}
} catch (err) {
console.log(err.name);
}
for (const fruit of Object.keys(stock)) console.log("key:", fruit);
for (const count of Object.values(stock)) console.log("value:", count);
for (const [fruit, count] of Object.entries(stock)) console.log(`${fruit} → ${count}`);
TypeError
key: apples
key: pears
value: 4
value: 0
apples → 4
pears → 0
for (const [key, value] of Object.entries(obj)) is the modern idiom for looping over an object's own data.
Iterating null or undefined
for...of over null or undefined throws a TypeError, since neither is iterable. If a list might be missing, default it: for (const x of items ?? []).
for...in: the keys of an object
for (const key in object) statement
for...in is as old as JavaScript. It runs the body once for each enumerable string-keyed property of the object, including inherited ones, and always gives you the key as a string:
const order = { id: 7, total: 42 };
for (const key in order) {
console.log(key, order[key]);
}
id 7
total 42
What it skips: properties keyed by symbols (article 19), and non-enumerable properties, which includes nearly all built-in methods like toString. Over null or undefined, it simply doesn't run, without an error.
The inherited-properties trap
Because for...in walks the prototype chain, it can visit properties that aren't the object's own:
const defaults = { theme: "light" };
const settings = Object.create(defaults); // settings inherits from defaults
settings.fontSize = 14;
const viaForIn = [];
for (const key in settings) viaForIn.push(key);
console.log(viaForIn);
console.log(Object.keys(settings)); // own properties only
[ 'fontSize', 'theme' ]
[ 'fontSize' ]
Old code guarded every for...in with if (obj.hasOwnProperty(key)) for this reason (ESLint's guard-for-in rule asks for it). Modern code usually uses Object.keys/Object.entries with for...of instead, which only see own properties.
Never use for...in on arrays
for...in gives array indexes as strings, includes any extra properties, and isn't meant for ordered iteration:
const colors = ["red", "green"];
colors.note = "sale";
const keys = [];
for (const k in colors) keys.push(`${k} (${typeof k})`);
console.log(keys);
const nextIndexes = [];
for (const i in [10, 20]) nextIndexes.push(i + 1); // "0" + 1 is "01"
console.log(nextIndexes);
[ '0 (string)', '1 (string)', 'note (string)' ]
[ '01', '11' ]
String indexes break arithmetic, as the second loop shows. Use for...of, entries() or a classic for for arrays. Libraries that add enumerable properties to Array.prototype (rare today, common in the 2000s) would make for...in visit those too.
Property order
Both for...in and Object.keys/entries use the same order for own properties: integer-like keys first, in ascending numeric order, then other string keys in insertion order:
const mixed = { b: 1, a: 2, 10: "ten", 2: "two" };
console.log(Object.keys(mixed));
[ '2', '10', 'b', 'a' ]
So objects aren't a good way to keep numeric IDs in insertion order: { 30: ..., 4: ... } comes back as 4, 30. Use a Map or an array when order matters.
for...of vs for...in at a glance
for...of | for...in | |
|---|---|---|
| Gives you | values | property names (strings) |
| Works on | iterables: arrays, strings, Maps, Sets, generators | any object |
| Plain objects | TypeError (use Object.entries) | yes |
| Inherited properties | n/a | included if enumerable |
null / undefined | TypeError | skipped silently |
| Use for | almost all iteration | rare: inspecting objects' keys, including inherited ones |
Changing a collection while looping
Array iteration is live: the iterator checks the current length at each step, so elements pushed during the loop are visited too. The same holds for Sets and Maps:
const queue = [1, 2];
for (const job of queue) {
if (queue.length < 5) queue.push(job * 10);
}
console.log(queue);
[ 1, 2, 10, 20, 100 ]
That's exactly right for a work queue where processing one job can add more, and exactly wrong if you didn't expect it; without the length guard, this loop would never end. Iterate over a copy (for (const x of [...list])) when the body modifies the collection and you want a fixed set of items.
Holes in arrays
for...of visits array holes as undefined, while forEach, map and filter skip them (part 7):
const sparse = [1, , 3];
const viaOf = [];
for (const v of sparse) viaOf.push(v);
const viaForEach = [];
sparse.forEach((v) => viaForEach.push(v));
console.log(viaOf, viaForEach);
[ 1, undefined, 3 ] [ 1, 3 ]
Leaving early, and cleanup
break and return end a for...of loop early (article 43). When they do, the loop tells the iterator it's finished, which lets generators and other iterators clean up, for example by closing a file:
function* readRecords() {
try {
yield "record 1";
yield "record 2";
yield "record 3";
} finally {
console.log("closing the source");
}
}
for (const record of readRecords()) {
console.log(record);
if (record === "record 2") break;
}
record 1
record 2
closing the source
This is one practical advantage of for...of over forEach: forEach can't be stopped except by throwing an exception.
for await...of
For data that arrives asynchronously, such as a stream read chunk by chunk, paginated API results or events, there's for await...of. It works inside async functions (and at the top level of modules), and waits for each value before running the body:
async function* fetchPages() {
yield ["a", "b"]; // imagine each page coming from a network request
yield ["c"];
}
async function main() {
const items = [];
for await (const page of fetchPages()) {
items.push(...page);
}
console.log(items);
}
main();
[ 'a', 'b', 'c' ]
Node.js streams and the web ReadableStream (in modern runtimes) are async iterables, so for await (const chunk of stream) reads them. Part 13 covers asynchronous iteration properly.
Common questions
for...of or forEach?
Both visit each element. for...of supports break, continue, return and await in its body, and works on any iterable. forEach only exists on arrays, Maps, Sets and some DOM collections, can't be stopped early, and ignores await inside its callback. Prefer for...of for loops with control flow; forEach is fine for simple one-liners.
Can I use for...of with a NodeList from querySelectorAll?
Yes. NodeList is iterable in all modern browsers: for (const el of document.querySelectorAll(".item")). The older HTMLCollection (from getElementsByClassName) is iterable too.
Does for...in work on strings?
It does, giving the indexes "0", "1", ... as strings, which is never what you want. Use for...of for characters.
Is the order of for...in guaranteed?
For own properties, since ES2020, yes: the same integer-then-insertion order as Object.keys. For inherited properties it's more loosely specified. Don't rely on order for anything important; use an array or Map.
Summary
for (const v of iterable)loops over values of arrays, strings (by code point), Maps, Sets, generators and other iterables.- Get indexes with
arr.entries(); loop over objects withObject.keys,Object.valuesorObject.entries. for (const k in obj)loops over enumerable string keys, own and inherited. Avoid it for arrays.- Own keys come in order: integer-like keys ascending, then other keys in insertion order.
- Array iteration is live: elements added during the loop are visited.
break/returninfor...ofcloses the iterator so it can clean up;for await...ofiterates asynchronous sources.
Practice Questions
What does this print?
const out = [];
for (const x in ["a", "b"]) out.push(x + x);
console.log(out);
Answer
[ '00', '11' ]. for...in gives the indexes as strings, and + concatenates them.
Count how many times each word in this array appears, using for...of and a Map.
const words = ["to", "be", "or", "not", "to", "be"]
Answer
const counts = new Map();
for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
The result maps to → 2, be → 2, or → 1, not → 1.
Why does for (const [k, v] of user) throw for this object, and what's the fix?
const user = { name: "Ana" }
Answer
Plain objects aren't iterable, so for...of can't get an iterator. Use for (const [k, v] of Object.entries(user)).
In what order does this code visit the keys?
for (const k in { z: 1, 5: 2, a: 3, 1: 4 })
Answer
"1", "5", "z", "a": integer-like keys first in ascending order, then the other keys in the order they were added.
Previous: JavaScript Loops: while, do/while and the Classic for Loop
Next: JavaScript Jump Statements: break, continue, Labels and return

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.