For...Of Loops
A for...of loop visits the values of an iterable, one per pass. Arrays, strings, Set, Map, typed arrays, arguments and the NodeList that querySelectorAll() returns are all iterable. It is the simplest way to go through every item of a list when you do not need to manage an index yourself.
Looping over an array
Section titled “Looping over an array”On each pass, the loop variable holds the next item:
const playlist = ['Intro', 'Rain', 'Outro'];
for (const track of playlist) { console.log(track);}This prints:
IntroRainOutroThe variable can be declared with const, because each pass gets a fresh binding. Use let only if the body reassigns it.
for…of compared with for…in
Section titled “for…of compared with for…in”for...in visits property names, and for...of visits values. On an array, for...in gives the indexes as strings and also picks up any other property added to the array, while for...of gives only the items:
const playlist = ['Intro', 'Rain', 'Outro'];playlist.label = 'favourites';
for (const key in playlist) { console.log('in:', key);}
for (const value of playlist) { console.log('of:', value);}This prints:
in: 0in: 1in: 2in: labelof: Introof: Rainof: OutroUse for...of for arrays and other lists, and for...in only for the keys of a plain object.
Getting the index as well
Section titled “Getting the index as well”When the index is needed too, loop over entries(), which yields [index, value] pairs, and unpack each pair with array destructuring:
const playlist = ['Intro', 'Rain', 'Outro'];
for (const [index, track] of playlist.entries()) { console.log(`${index + 1}. ${track}`);}This prints:
1. Intro2. Rain3. OutroStrings, Sets and Maps
Section titled “Strings, Sets and Maps”A string yields its characters, a Set yields its values, and a Map yields [key, value] pairs:
for (const char of 'café🙂') { console.log(char);}
const visited = new Set(['Oslo', 'Lima', 'Oslo']);for (const city of visited) { console.log(city);}
const stock = new Map([['pens', 12], ['pads', 4]]);for (const [item, count] of stock) { console.log(item, count);}This prints:
café🙂OsloLimapens 12pads 4A string is iterated by Unicode code point, so the emoji arrives whole, even though it takes two UTF-16 code units and indexing with [i] would split it in half. A character built from several code points, such as a flag or a family emoji, still arrives in pieces. Intl.Segmenter splits text into the characters a reader sees.
Plain objects are not iterable
Section titled “Plain objects are not iterable”A plain object has no defined sequence of values, so for...of throws a TypeError on one. Loop over Object.entries(), Object.keys() or Object.values() instead:
const order = { pens: 12, pads: 4 };
try { for (const entry of order) { console.log(entry); }} catch (error) { console.log(error.message);}
for (const [item, count] of Object.entries(order)) { console.log(item, count);}This prints:
order is not iterablepens 12pads 4An object can be made iterable by giving it a Symbol.iterator method, which Custom iterators for for…of loops covers.
Stopping early
Section titled “Stopping early”break and continue work in for...of as they do in any loop. This is one advantage over forEach(), which can be stopped part way only by throwing an error:
const readings = [3, 7, 12, 5];
for (const value of readings) { if (value > 10) { console.log(`first value over 10: ${value}`); break; }}This prints:
first value over 10: 12Steve Griffith covers this topic in his video JavaScript for…of loops.