JavaScript Loops "for ... of" loop


Example

6
const iterable = [0, 1, 2];
for (let i of iterable) {
    console.log(i);
}

Expected output:

0
1
2

The advantages from the for...of loop are:

  • This is the most concise, direct syntax yet for looping through array elements
  • It avoids all the pitfalls of for...in
  • Unlike forEach(), it works with break, continue, and return

Support of for...of in other collections

Strings

for...of will treat a string as a sequence of Unicode characters:

const string = "abc";
for (let chr of string) {
  console.log(chr);
}

Expected output:

a b c

Sets

for...of works on Set objects.

Note:

const names = ['bob', 'alejandro', 'zandra', 'anna', 'bob'];

const uniqueNames = new Set(names);

for (let name of uniqueNames) {
  console.log(name);
}

Expected output:

bob
alejandro
zandra
anna

Maps

You can also use for...of loops to iterate over Maps. This works similarly to arrays and sets, except the iteration variable stores both a key and a value.

const map = new Map()
  .set('abc', 1)
  .set('def', 2)

for (const iteration of map) {
  console.log(iteration) //will log ['abc', 1] and then ['def', 2]
}

You can use destructuring assignment to capture the key and the value separately:

const map = new Map()
  .set('abc', 1)
  .set('def', 2)

for (const [key, value] of map) {
  console.log(key + ' is mapped to ' + value)
}
/*Logs:
  abc is mapped to 1
  def is mapped to 2
*/

Objects

for...of loops do not work directly on plain Objects; but, it is possible to iterate over an object’s properties by switching to a for...in loop, or using Object.keys():

const someObject = { name: 'Mike' };

for (let key of Object.keys(someObject)) {
  console.log(key + ": " + someObject[key]);
}

Expected output:

name: Mike