for. . . of
Walks the successive values of an iterable object: an array, a string, a Map, a Set, and others.
Example
#const skills = ['HTML', 'CSS', 'JavaScript']
for (const skill of skills) {
console.log(`Learning: ${skill}`)
}Definition and usage
#On every turn, a for...of loop hands you the next value from an iterable object. You don’t have to manage a counter or reach for an element by index, so the code is shorter and less prone to off-by-one errors.
It works with arrays, strings (character by character, without splitting emoji in half), Map and Set objects, querySelectorAll() lists, and generators. A plain object {} is not iterable, so you walk its contents with Object.keys(), Object.values(), or Object.entries().
Unlike forEach(), for...of lets you use break, continue, return, and await. When you also need the index, use array.entries() with destructuring: for (const [index, value] of array.entries()).
Syntax
#for (const element of iterable) {
// statements
}More examples
#const tasks = ['Variables', 'Loops', 'Functions']
for (const [index, task] of tasks.entries()) {
console.log(index, task)
}const scores = { Emma: 120, Jack: 95 }
for (const [name, points] of Object.entries(scores)) {
console.log(`${name} has ${points} pts`)
}const word = 'Code👾'
for (const char of word) {
console.log(char)
}
console.log(word.length)for...of walks whole Unicode characters, so the emoji is a single element, even though length counts it as 2.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#for...ofgives you values,for...ingives you keys. For arrays, you almost always wantfor...of.- With
awaitinside the loop, the operations run one after another. To run them in parallel, collect the promises into an array and usePromise.all(). - Declare the loop variable with
const. Every turn gets a new variable, so an accidental overwrite reports an error right away.
Related entries
#- for...in vs for...offor...of hands you the successive values of an iterable object, while for...in hands you the successive property names of an object as strings.
- for...inWalks the names of an object’s enumerable properties, including ones inherited from the prototype.
- forA loop with a counter: initialization, condition, and step. Repeats a block of code while the condition is true.
- Object.entries()Returns an array of an object’s [key, value] pairs.
- DestructuringDestructuring pulls values out of arrays and objects straight into separate variables.
- MapA collection of key-value pairs where the key can be any value and insertion order is preserved.
- SetA collection of unique values: each value can appear in the set only once.
Spotted a mistake or missing an example? Write to us.