Understanding the difference between for of vs for in JavaScript is a fundamental milestone for any developer moving beyond basic syntax into writing clean, predictable, and performant code. Practically speaking, while both loops iterate over data structures, they operate on fundamentally different principles: one iterates over values of iterable objects, while the other enumerates property keys (usually strings) of an object. Choosing the wrong one can lead to subtle bugs, unexpected type coercion, or performance bottlenecks, especially when dealing with arrays, strings, Maps, Sets, or plain objects.
The Core Distinction: Values vs. Keys
At the highest level, the mental model is simple. The for...of loop is designed for iterables—things you can consume one item at a time, like a conveyor belt. Which means it gives you the value directly. So the for... Because of that, in loop is designed for enumerables—specifically, the string-keyed properties of an object. It gives you the key (property name), requiring you to manually access the value if needed.
This distinction dictates everything about when and how you should use them.
Deep Dive: The for...of Loop
Introduced in ES6 (ES2015), for...of is the modern standard for iterating over data collections. Still, it works on any object that implements the Iterable Protocol (meaning it has a Symbol. iterator method). This includes Arrays, Strings, Maps, Sets, NodeLists, arguments objects, and even Generators.
Syntax and Basic Usage
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color);
}
// Output: "red", "green", "blue"
Notice the variable declaration uses const. Because the loop creates a new binding for each iteration, const is perfectly safe and preferred for immutability within the block scope.
Why for...of Wins for Arrays
Historically, developers used for loops with index counters or forEach. Here's the thing — for... of combines the readability of forEach with the control flow capabilities of a standard for loop.
Key Advantages:
- Break and Continue: Unlike
forEach, you canbreakout of afor...ofloop early orcontinueto the next iteration. This is critical for search algorithms or performance optimization. - Async/Await Support: You can
awaitpromises sequentially inside afor...ofloop. This is impossible withforEachwithout complex Promise chaining.async function fetchUserData(userIds) { const results = []; for (const id of userIds) { // Waits for each fetch to finish before the next starts const data = await fetch(`/api/users/${id}`).then(r => r.json()); results.push(data); } return results; } - Destructuring Support: You can destructure values directly in the loop declaration, which is incredibly powerful for Maps or arrays of tuples.
const map = new Map([['a', 1], ['b', 2]]); for (const [key, value] of map) { console.log(`${key}: ${value}`); }
Iterating Strings and NodeLists
for...of treats strings as sequences of Unicode code points (grapheme clusters), avoiding the classic "split surrogate pair" bug found in older iteration methods Which is the point..
const emoji = '👨👩👧👦'; // Family emoji (complex sequence)
for (const char of emoji) {
console.log(char); // Logs the whole emoji as one character
}
It also works natively on DOM collections like NodeList and HTMLCollection without needing Array.from() or spread syntax first.
Deep Dive: The for...in Loop
The for...in loop has existed since the very first version of JavaScript. Which means it does not use the Iterator protocol. Its sole purpose is to iterate over the enumerable string properties of an object. It looks at the object's own properties and properties inherited up the prototype chain.
Syntax and Basic Usage
const car = {
make: 'Toyota',
model: 'Camry',
year: 2022
};
for (const prop in car) {
console.log(`${prop}: ${car[prop]}`);
}
// Output: "make: Toyota", "model: Camry", "year: 2022"
The Prototype Chain Trap
This is the most dangerous aspect of for...in. But if an object inherits properties from a prototype (which almost all objects do), for... in will enumerate those inherited properties too Easy to understand, harder to ignore..
Object.prototype.customMethod = function() {}; // Polluting global prototype (bad practice, but happens)
const data = { a: 1, b: 2 };
for (const key in data) {
console.log(key); // Logs "a", "b", AND "customMethod"
}
The Fix: You must use hasOwnProperty() (or the modern Object.hasOwn()) to filter only the object's own properties Still holds up..
for (const key in data) {
if (Object.hasOwn(data, key)) { // Safe check
console.log(key);
}
}
Why for...in is Bad for Arrays
Using for...in on arrays is widely considered an anti-pattern for several reasons:
- Keys are Strings: The iteration variable is a string (
"0","1","2"), not a number. This forces implicit type coercion if you do math (index + 1becomes"01"). - Order Not Guaranteed: While modern engines typically iterate integer indices in order, the spec only guarantees order for integer keys if no non-integer keys exist. It is not reliable for ordered data processing.
- Sparse Arrays: It visits all enumerable properties, including array methods added to
Array.prototypeor "holes" in sparse arrays (depending on implementation), leading toundefinedvalues. - Performance: It is significantly slower than
for...ofor a standard index loop because of the prototype chain walking and string key handling.
Head-to-Head Comparison Table
| Feature | for...Practically speaking, of |
for... in |
|---|---|---|
| Primary Target | Iterables (Arrays, Maps, Sets, Strings, etc. |
Practical Decision Matrix: Which One Do I Choose?
Scenario 1: Looping through an Array or Array-like structure
Use for...of.
It gives you the value directly
Scenario 2 – Looping Through an Object (Plain Object or Class Instance)
When the target is a plain object or an instance of a class, for...in is the only statement that directly enumerates all enumerable property names, including inherited ones.
If you only want the properties that belong to the object itself, you must guard against prototype pollution:
const config = { timeout: 5000, retries: 3 };
for (const key in config) {
if (Object.hasOwn(config, key)) { // ← filters out inherited props
console.log(`${key}:`, config[key]);
}
}
An alternative that avoids the extra prototype check is Object.keys. It returns an array of the object’s own keys, which can then be iterated with forEach, reduce, or a classic for loop Less friction, more output..
Object.keys(config).forEach(key => {
console.log(`${key}:`, config[key]);
});
Scenario 3 – Iterating Over a Map
Map is an iterable collection. Its iterator yields entries ([key, value]) in insertion order, making for...of the natural choice:
const scores = new Map([['alice', 42], ['bob', 37]]);
for (const [name, points] of scores) {
console.log(`${name} scored ${points}`);
}
If you need only the values, for...That said, of still works (the destructuring pattern can be omitted). If you need only the keys, Map.keys() returns an iterator that can be consumed with for...of as well.
Scenario 4 – Iterating Over a Set
Like Map, a Set is iterable. The iterator yields values (no keys), so for...of is again the most straightforward approach:
const tags = new Set(['js', 'web', 'performance']);
for (const tag of tags) {
console.log(tag);
}
Because a Set does not have duplicate entries, for...of guarantees each value appears exactly once, and the order is insertion‑based.
Scenario 5 – Async Iteration (for‑await‑of)
When the iterable is asynchronous—for example, an async generator, an async iterable returned by an API—for...of evolves into for await of. This construct lets you await each yielded value without nesting async/await callbacks:
async function streamLogs() {
const iterator = getAsyncLogStream(); // returns an async iterator
for await (const entry of iterator) {
console.log(entry);
}
}
for...in does not support async iteration; attempting to use it would require manually managing the iterator’s next() method and awaiting each promise, which quickly becomes unwieldy That's the whole idea..
Scenario 6 – When You Need Both Keys and Values
Sometimes you want to transform an object’s entries into a new structure (e.g., an array of [key, value] pairs). In practice, the idiomatic way is to combine Object. entries with `for.. And that's really what it comes down to..
const entries = Object.entries(config); // → [['timeout', 5000], ['retries', 3]]
for (
```javascript
const [key, value] of entries) {
console.log(`${key} = ${value}`);
}
This combines Object.of’s clean iteration protocol. entries returns an array of the object’s own enumerable string-keyed properties, the loop stays synchronous and avoids the prototype chain entirely. entries with for...If symbol keys matter, use Reflect.But because Object. ownKeys or Object.getOwnPropertySymbols as appropriate That's the part that actually makes a difference..
Choosing the Right Loop
A simple decision guide helps avoid most confusion:
- Plain object keys or values → prefer
Object.keys,Object.values, orObject.entrieswithfor...of. - Arrays, strings,
Map,Set, generators → usefor...of. - Async streams or async iterables → use
for await...of. - Inherited enumerable properties are genuinely required → use
for...in, ideally with an own-property check. - Arrays → avoid
for...in; it enumerates index strings and can include inherited or non-index properties.
Common Pitfalls
for...in is not a general-purpose value iterator. Now, for... of, by contrast, requires an iterable; a plain object is not iterable by default, so for...In real terms, of over an object literal will throw unless you first obtain an iterable such as Object. Day to day, hasOwn guard appears so often. It walks property names, including inherited enumerable ones, which is why the Object.entries(obj).
It is also worth remembering that for...Day to day, of respects the iterable’s protocol. For a Map, that means entries; for a Set, values; for an array, elements. This consistency is what makes for...of predictable across built-in collections.
Conclusion
for...of to get explicit, own-property iteration without prototype surprises. of are not interchangeable. Even so, in and for... When working with plain objects, combine Object.ofconsumes iterable values and is the clearer choice for arrays, strings,Map, Set, generators, and async streams. Because of that, for... keys, Object.Also, for... Think about it: values, or Object. entries with for...in enumerates property names and is best reserved for object-property inspection where inherited properties are either filtered out or intentionally included. Choosing the loop that matches the data structure keeps code readable, avoids subtle bugs, and makes intent obvious to the next reader And that's really what it comes down to..