Tutorials JavaScript for...in & for...of
Ch 21 / 78
Chapter 21 Intermediate 7 min read JavaScript

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.

What you'll learn
for...in — iterating over object property keys
for...of — iterating over iterable values
What makes a value "iterable" in JavaScript
for...of with arrays, strings, Maps and Sets
Inherited properties & hasOwnProperty gotcha
for...in vs for...of vs for — when to use each

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:

for...in
Key Enumerator
Iterates over the enumerable property keys of an object — including inherited ones. Gives you the key name (string) on each iteration.
Use when: inspecting or copying object properties, debugging, dynamic key access.
for...of
Value Iterator
Iterates over the values of any iterable — arrays, strings, Maps, Sets, generators. Gives you the value directly.
Use when: looping array items, characters, Map entries, Set members — any iterable.
for (classic)
Index-Controlled Loop
Full control over init, condition and update. Best when you need the index, iterate backwards, or step by more than 1.
Use when: index matters, reverse loops, custom step increments, or breaking by position.

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.

for (const key in object) {
  // key holds the property name (always a string)
  object[key]  // ← access the value via bracket notation
}
key — the property name on each iteration (string) object — any object with enumerable properties object[key] — bracket notation to read the value
for...in — execution order
1 Collect enumerable keys of the object (own + inherited)
2 Assign next key to the loop variable as a string
3 Run body — use bracket notation to get the value
4 Repeat steps 2–3 until all keys are exhausted
for...in — watch out for
! Inherited keys from the prototype chain are also visited
! Array indices are enumerated as strings, not numbers
! Order is not guaranteed (though modern engines are consistent)
! Never use on arrays — use for...of or forEach instead
JavaScript — for...in Loop
// ── 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 risk
Avoid on Arrays
Never use for...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.

for (const value of iterable) {
  // value is the item on each iteration
  // no bracket notation required — value is direct
}
value — the current element's value on each iteration iterable — arrays, strings, Maps, Sets, generators… Destructuring works: const [k, v] of map
for...of — execution order
1 Call Symbol.iterator on the iterable to get an iterator
2 Call iterator.next() — get { value, done }
3 If done is false — assign value, run body
4 Repeat steps 2–3 until done === true
Iterables for...of supports
✓ Array — each element value in order
✓ String — each Unicode character
✓ Map — each [key, value] pair
✓ Set — each unique value in insertion order
JavaScript — for...of Loop
// ── 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)
}
Destructuring in for...of
You can use array destructuring directly in the 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.

JavaScript — entries(), keys(), values()
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...of

for...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
Yes
No (use Object.entries)
No
Works on arrays
Avoid
Yes (recommended)
Yes
Works on strings
Avoid
Yes (characters)
Yes (indices)
Works on Map / Set
No
Yes
No
Includes inherited keys
Yes (use hasOwnProperty)
No No
Supports break / continue
Yes
Yes
Yes
Introduced in ES1 (original) ES6 (2015) ES1 (original)
JavaScript — Same Array, Three Ways
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:

break
Immediately stops the iteration and exits the loop entirely. Not possible with forEach or map.
continue
Skips the current iteration and moves to the next key (for...in) or next value (for...of).
JavaScript — break & continue
// ── 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 exit

Real-World Use Cases

Here are the practical scenarios where each loop form excels in day-to-day JavaScript and front-end development:

Inspect Object Keys
Log, clone or transform all properties of a config or data object dynamically.
for...in
Render a List
Loop over an array of items to build HTML, display rows in a table, or render React components.
for...of
Iterate a Map
Loop over key-value pairs in a Map with destructuring for clean, readable access.
for...of
Process Characters
Iterate over each character in a string — great for validation, encoding, or building patterns.
for...of
Deduplicate with Set
Use a Set to remove duplicates, then for...of to process each unique value cleanly.
for...of
Early Exit Search
Use for...of with break to stop iterating the moment a match is found — impossible with forEach.
for...of

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.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These patterns appear constantly in real JavaScript codebases. Each uses for...in or for...of to solve a specific task concisely.

JavaScript — for...in & for...of Recipes
// ── 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 }
Quick Check
What does for...in give you on each iteration of an object?
Quick Check
Which of these is NOT iterable with for...of?
Quick Check
How do you use for...of to get both the index and value from an array?
Chapter Summary
  • 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 prefer Object.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...of or forEach instead.
  • 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 with for...of. Use Object.entries(obj), Object.keys(obj), or Object.values(obj) to bridge the gap.
  • To get both index and value from an array with for...of, use arr.entries() with destructuring: for (const [i, val] of arr.entries()).
  • Both for...in and for...of support break and continue — an advantage over forEach and map, 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel