🔍 Understanding `of` in JavaScript – `for...of` Loop Deep Dive
Category: js / general-concepts
Difficulty: hard
In JavaScript, the keyword of is used in the for...of loop— not an operator , but a language construct that allows iteration over iterable objects. 📌 Syntax [code example] element: variable that holds the current value iterable: object with an internal iterator (e.g. Array, String, Map, etc.) ✅ Supported Iterables Works with for...of ✅ String ✅ arguments ✅ (browser) Object 🔁 Example: Array [code example] 🔁 Example: String [code example] 🔁 Example: Map [code example] 🚫 for...of vs for...in for...of Values ❌ (unless iterable) ✅ Recommended Preserved (iterators) 🧪 Example Difference: [code example] 🔍 Under the Hood for...of uses the iterable protocol. When you do: [code example] JS internally does: [code example] 🛠 When to Use for...of You want values, not keys. You’re dealing with iterable data (arrays, strings, sets, maps). You want cleaner syntax than .forEach() or manual for loops. You need break, continue, or return—which forEach doesn't support. ⚠️ Caveats Doesn't work on plain objects unless you make them iterable. Can’t use async await inside—use for await...of for that. ✅ Conclusion The for...of construct is the canonical way to iterate over iterable values in modern JavaScript. It's readable, concise, and robust— avoid for...in for arrays or iterable data structures . <!-- quiz-start --> Q1: What does for...of iterate over? [ ] Object keys [ ] Array indexes [x] Iterable values [ ] Object properties including inherited ones Q2: Which of the following can you iterate with for...of? [ ] Plain objects {} [x] Arrays, Strings, Maps, and Sets [ ] Only arrays [ ] Only strings Q3: What is the key difference between for...of and for...in? [ ] for...of is faster than for...in [ ] for...in only works on arrays [x] for...of iterates over values, while for...in iterates over keys/property names [ ] There is no difference, they are interchangeable <!-- quiz-end -->...