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
for (const element of iterable) { // code block }
element: variable that holds the current valueiterable: object with an internal iterator (e.g.Array,String,Map, etc.)
β Supported Iterables
| Type | Works with for...of |
|---|---|
Array | β |
String | β |
Map,Set | β |
arguments | β (in ES6+) |
NodeList | β (browser) |
Object | β (not iterable) |
π Example: Array
const numbers = [10, 20, 30]; for (const num of numbers) { console.log(num); // 10, then 20, then 30 }
π Example: String
for (const char of 'Hi') { console.log(char); // 'H', 'i' }
π Example: Map
const map = new Map([['a', 1], ['b', 2]]); for (const [key, value] of map) { console.log(key, value); // 'a' 1, then 'b' 2 }
π« for...of vs for...in
| Feature | for...of | for...in |
|---|---|---|
| Iterates over | Values | Keys (property names) |
| Works on objects | β (unless iterable) | β |
| Use for arrays | β Recommended | β Avoid β includes inherited keys |
| Order | Preserved (iterators) | Not guaranteed |
π§ͺ Example Difference:
const arr = ['a', 'b']; for (const i in arr) { console.log(i); // 0, 1 (indexes as strings) } for (const val of arr) { console.log(val); // 'a', 'b' (actual values) }
π Under the Hood
for...of uses the iterable protocol. When you do:
for (const x of iterable) {}
JS internally does:
const iterator = iterable[Symbol.iterator](); let result; while (!(result = iterator.next()).done) { const x = result.value; // loop body }
π 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 manualforloops. - You need
break,continue, orreturnβwhichforEachdoesn't support.
β οΈ Caveats
- Doesn't work on plain objects unless you make them iterable.
- Canβt use async
awaitinsideβusefor await...offor 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 .
Quick Quiz
Test your understanding with 3 quick questions
Q1What does `for...of` iterate over?
Q2Which of the following can you iterate with `for...of`?
Q3What is the key difference between `for...of` and `for...in`?