The for...of Loop in JavaScript
🟢 Beginner Level | Iterable Value Iteration
📖 Definition
Introduced in **ES6**, the for...of loop creates a loop iterating over iterable objects (Arrays, Strings, Maps, Sets, NodeLists) yielding the **value** of each sequential property.
🤔 Purpose
Provides a clean, index-free iteration syntax for arrays and collections without needing manual length checks.
🌐 Multilingual Explanations
English
The for (const value of iterable) loop retrieves values directly, unlike for...in which retrieves object property keys.
Hindi
JavaScript mein for (const item of array) loop direct values read karta hai. Index counter i ki zaroorat nahi hoti.
Marathi
for...of loop mule array til values sahaj read karta etat.
Hinglish
Array iteration: for (const user of users) { console.log(user); } pattern follow karein.
📝 Syntax & Parameters
for (const value of iterableObject) {
// Body code block operating on value
}
⚡ Execution Flow
- Calls `[Symbol.iterator]()` method on target iterable object.
- Sequentially fetches `next().value` until `done` is true.
- Executes loop body per iteration step.
💡 Progressive Examples
Example 1: Iterating Arrays & Strings
const colors = ["Red", "Green", "Blue"];
for (const color of colors) {
console.log("Color:", color);
}
🖥️ Expected Output
Color: Red
Color: Green
Color: Blue
🔍 Line-by-Line Code Breakdown
for (const color of colors): Binds each string element directly to variablecolor.
⚠️ Variations & Edge Cases
Attempting to use for...of on plain JS objects `{}` throws a TypeError: object is not iterable (use `Object.keys()` or `for...in` instead).
❌ Common Beginner Mistakes
Using `for...of` on Plain Objects: Plain objects do not implement `[Symbol.iterator]`, resulting in runtime type errors.
🛠️ Real-World Practical Usage
Iterating over DOM `NodeList` collections returned by `document.querySelectorAll()`.
🎯 Tiered Practice Exercises
- Beginner: Write a `for...of` loop printing characters of a string.
- Intermediate: Iterate over a `Map` using `for...of` destructured `[key, value]` pairs.
- Advanced: Implement a custom `[Symbol.iterator]` on a class object for `for...of` support.