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.
| 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) |
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
// 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}`);
}
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}`);
}
How do you terminate a loop prematurely or skip a specific iteration? Proceed to: JavaScript Break and Continue Statements →
Accelerate your JavaScript mastery by studying these tightly connected core tutorials:
Indexed looping vs iterator-based looping.
Using forEach, map, filter, and reduce.
Enumerable property inspection with for..in.
Iterating over key-value pairs and unique sets.