for...in & for...of
ES6 introduced two elegant iteration statements —
for...in and for...of.
They replace verbose index-based loops for many everyday tasks:
for...in enumerates object keys,
while for...of iterates over
iterable values like arrays, strings, Maps and Sets.
Knowing which to reach for — and when to avoid each — is essential for writing
clean, expressive JavaScript.
JavaScript's Iteration Statements — Overview
JavaScript gives you four primary ways to loop. The classic for loop works by index. The newer for...in and for...of loops are higher-level: they express what you're iterating over, not how the counter works:
The for...in Loop
The for...in loop iterates
over all enumerable string-keyed properties of an object, including
those inherited from its prototype chain. On each iteration the loop variable
receives the property key (always a string), not the value.
// key holds the property name (always a string)
object[key] // ← access the value via bracket notation
}
// ── Basic for...in — iterating object keys ────────────────────
const user = { name: "Alice", age: 28, city: "Mumbai" };
for (const key in user) {
console.log(key, "→", user[key]);
}
// name → Alice
// age → 28
// city → Mumbai
// ── hasOwnProperty guard — skip inherited keys ────────────────
function Animal(type) { this.type = type; }
Animal.prototype.breathes = true; // inherited property
const cat = new Animal("cat");
for (const key in cat) {
console.log(key); // "type", "breathes" ← inherited also shown!
}
// ✓ Safer — only own properties
for (const key in cat) {
if (cat.hasOwnProperty(key)) {
console.log(key); // "type" only
}
}
// ── Modern alternative: Object.keys() ────────────────────────
Object.keys(user).forEach(key => console.log(key, user[key]));
// Only own enumerable keys — no prototype chain riskfor...in to loop over arrays.
It iterates array indices as strings, may visit inherited array
prototype properties, and gives no guarantee of numeric order.
Use for...of, forEach, or a classic
for loop for arrays instead.
The for...of Loop
The for...of loop iterates
over the values of any iterable object. Unlike
for...in, it gives you the actual value
directly — no bracket notation needed. It works with arrays, strings,
Maps, Sets, and any object that implements the
Symbol.iterator protocol.
// value is the item on each iteration
// no bracket notation required — value is direct
}
const [k, v] of map
{ value, done }
done === true
[key, value]
pair
// ── Arrays ────────────────────────────────────────────────────
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit); // apple banana cherry
}
// ── Strings — character by character ─────────────────────────
for (const char of "Hello") {
console.log(char); // H e l l o
}
// ── Map — [key, value] destructuring ─────────────────────────
const scores = new Map([
["Alice", 95], ["Bob", 82], ["Carol", 77]
]);
for (const [name, score] of scores) {
console.log(`${name}: ${score}`);
// Alice: 95 Bob: 82 Carol: 77
}
// ── Set — unique values ───────────────────────────────────────
const tags = new Set(["js", "css", "js", "html"]);
for (const tag of tags) {
console.log(tag); // js css html (duplicate removed)
}for...of header. This is especially clean when iterating a
Map: for (const [key, value] of myMap) — no manual indexing
needed. Works with entries() on arrays too:
for (const [i, val] of arr.entries()).
Getting Both Index and Value — entries()
for...of gives you values
but not indices. When you need both, pair it with the
.entries() method, which returns
[index, value] pairs. This combines the readability of
for...of with the index tracking of a classic
for loop.
const colors = ["red", "green", "blue"];
// ── entries() — index + value ─────────────────────────────────
for (const [i, color] of colors.entries()) {
console.log(`${i}: ${color}`);
}
// 0: red 1: green 2: blue
// ── keys() — indices only ─────────────────────────────────────
for (const i of colors.keys()) {
console.log(i); // 0 1 2
}
// ── values() — values only (same as plain for...of) ──────────
for (const color of colors.values()) {
console.log(color); // red green blue
}
// ── Object.entries() — for...of over objects ─────────────────
const user = { name: "Alice", age: 28, city: "Mumbai" };
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}
// name: Alice age: 28 city: Mumbai
// ↑ This is the recommended way to loop over plain objects with for...offor...in vs for...of vs for
Choosing the right iteration form depends on what you're iterating and what you need on each step. Here's a definitive comparison:
| Feature | for...in | for...of | for (classic) |
|---|---|---|---|
| Iterates over | Object keys | Iterable values | Index-controlled |
| Variable receives | Key (string) | Value (any type) | Counter variable |
| Works on plain objects |
|
|
|
| Works on arrays |
|
|
|
| Works on strings |
|
|
|
| Works on Map / Set |
|
|
|
| Includes inherited keys |
|
No | No |
| Supports break / continue |
|
|
|
| Introduced in | ES1 (original) | ES6 (2015) | ES1 (original) |
const arr = ["a", "b", "c"];
// ── for (classic) — index access ─────────────────────────────
for (let i = 0; i < arr.length; i++) {
console.log(i, arr[i]); // 0 "a" 1 "b" 2 "c"
}
// ── for...in — ⚠ gives indices as strings, avoid on arrays
for (const i in arr) {
console.log(i, arr[i]); // "0" "a" "1" "b" "2" "c" ← string keys!
}
// ── for...of — ✓ clean, values only ──────────────────────────
for (const item of arr) {
console.log(item); // "a" "b" "c"
}
// ── for...of + entries() — ✓ index AND value ─────────────────
for (const [i, item] of arr.entries()) {
console.log(i, item); // 0 "a" 1 "b" 2 "c"
}break & continue in for...in / for...of
Both for...in and
for...of support
break and
continue just like classic loops.
This is one advantage they hold over
forEach, which cannot be exited early:
forEach or map.// ── break in for...of — stop when target found ───────────────
const nums = [1, 2, 3, 4, 5];
for (const n of nums) {
if (n === 3) break;
console.log(n); // 1 2
}
// ── continue in for...of — skip odd numbers ───────────────────
for (const n of nums) {
if (n % 2 !== 0) continue;
console.log(n); // 2 4
}
// ── break in for...in — stop after first key ─────────────────
const config = { host: "localhost", port: 3000, debug: true };
for (const key in config) {
if (key === "port") break;
console.log(key, config[key]); // "host" "localhost"
}
// ── forEach cannot break — for...of is better here ───────────
// nums.forEach(n => { if (n === 3) break; }); // ← SyntaxError!
// Use for...of when you need early exitReal-World Use Cases
Here are the practical scenarios where each loop form excels in day-to-day JavaScript and front-end development:
Try It — Live Editor
Experiment with for...in
and for...of below. Modify the object, arrays,
strings and collections to see the difference in what each loop produces.
Common Patterns & Recipes
These patterns appear constantly in real JavaScript codebases.
Each uses for...in or
for...of to solve a specific task concisely.
// ── Shallow clone an object ───────────────────────────────────
function clone(obj) {
const copy = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) copy[key] = obj[key];
}
return copy;
}
// ── Sum array values ──────────────────────────────────────────
const prices = [19.99, 4.50, 34.00];
let total = 0;
for (const p of prices) total += p;
console.log(total.toFixed(2)); // "58.49"
// ── Find first match and break ────────────────────────────────
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Carol" }
];
let found;
for (const u of users) {
if (u.id === 2) { found = u; break; }
}
// ── Reverse a string using for...of ──────────────────────────
function reverseStr(str) {
let result = "";
for (const ch of str) result = ch + result;
return result;
}
reverseStr("hello"); // "olleh"
// ── Frequency map with for...of ───────────────────────────────
const letters = ["a", "b", "a", "c", "b", "a"];
const freq = {};
for (const l of letters) freq[l] = (freq[l] || 0) + 1;
// { a: 3, b: 2, c: 1 }
// ── Object key-value transform with Object.entries ────────────
const prices2 = { apple: 1.2, banana: 0.5, cherry: 3.0 };
const discounted = {};
for (const [fruit, price] of Object.entries(prices2)) {
discounted[fruit] = +(price * 0.9).toFixed(2); // 10% off
}
// { apple: 1.08, banana: 0.45, cherry: 2.7 }for...in give you on each iteration of an object?
for...of?
for...of to get both the index and value from an
array?- for...in iterates over all enumerable property keys of an object
as strings — including inherited keys from the prototype chain. Always use
hasOwnProperty()guard or preferObject.keys()to stay safe. - Never use for...in on arrays — it yields indices as strings, may include
inherited array methods, and doesn't guarantee numeric order. Use
for...oforforEachinstead. - for...of iterates over the values of any iterable — arrays,
strings, Maps, Sets, generators, and any object implementing
Symbol.iterator. It gives you the value directly, not the key. - Plain objects
{ }are not iterable withfor...of. UseObject.entries(obj),Object.keys(obj), orObject.values(obj)to bridge the gap. - To get both index and value from an array with
for...of, usearr.entries()with destructuring:for (const [i, val] of arr.entries()). - Both
for...inandfor...ofsupport break and continue — an advantage overforEachandmap, which cannot be exited early. - Use for...in for inspecting, cloning or transforming plain objects; use for...of for everything iterable — arrays, strings, Maps, Sets.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.