Loading article...
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.
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.)| Type | Works with for...of |
|---|---|
Array | β |
String | β |
Map,Set | β |
arguments | β (in ES6+) |
NodeList | β (browser) |
Object | β (not iterable) |
const numbers = [10, 20, 30]; for (const num of numbers) { console.log(num); // 10, then 20, then 30 }
for (const char of 'Hi') { console.log(char); // 'H', 'i' }
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 |
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) }
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 }
for...of.forEach() or manual for loops.break, continue, or returnβwhich forEach doesn't support.await insideβuse for await...of for that.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 .
Test your understanding with 3 quick questions