JavaScript For..In vs For..Of: Iterating Keys vs Traversing Values

One of the most frequent points of confusion for JavaScript developers is choosing between for..in and for..of. Although their syntax looks nearly identical, they serve completely different purposes.

The Golden Distinction Table

Feature for..in Loop for..of Loop (ES6)
Primary Target Objects (Key-value structures) Iterables (Arrays, Strings, Maps, Sets)
What it Retrieves Property KEYS / Names (Strings) Element VALUES
Prototype Chain Traverses inherited enumerable properties Ignores prototype; uses [Symbol.iterator]
Works on Objects? Yes natively Throws TypeError (Plain objects not iterable)

1. for..in Loop (Iterating Object Properties)

const student = {
    name: "Vikram",
    branch: "Computer Science",
    semester: 4
};

for (const key in student) {
    console.log(`Property: ${key} === Value: ${student[key]}`);
}
// Output:
// Property: name === Value: Vikram
// Property: branch === Value: Computer Science
// Property: semester === Value: 4

2. for..of Loop (Iterating Iterable Values)

// Iterating an Array
const scores = [95, 88, 92];
for (const score of scores) {
    console.log("Score value:", score); // 95, 88, 92 (Values directly!)
}

// Iterating a String (Character by Character)
for (const char of "JS") {
    console.log("Character:", char); // 'J', 'S'
}

// Iterating with Index via entries()
for (const [index, score] of scores.entries()) {
    console.log(`Index ${index}: ${score}`);
}

University Exam Corner (BCA Examination Notes)

Viva Question: "Can you use for..of on a plain JavaScript object? How can you iterate an object's values cleanly?"

Answer: No, attempting for (const val of myObj) throws TypeError: myObj is not iterable because plain objects lack a [Symbol.iterator] method.
To iterate cleanly, use Object.values(myObj) or Object.entries(myObj):

for (const [key, val] of Object.entries(student)) {
    console.log(`${key}: ${val}`);
}

Next Step

How do you terminate a loop prematurely or skip a specific iteration? Proceed to: JavaScript Break and Continue Statements →

Explore Related JavaScript Tutorials

Accelerate your JavaScript mastery by studying these tightly connected core tutorials:

Standard For Loop →

Indexed looping vs iterator-based looping.

Array Functional Iteration →

Using forEach, map, filter, and reduce.

Objects & Properties →

Enumerable property inspection with for..in.

Map & Set Collections →

Iterating over key-value pairs and unique sets.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!