for of loop

mohananagavenkat profile image Mohana Naga Venkat Sayempu ・1 min read

The new for of loop is designed to work exclusively with iterable objects. The loop calls the next function behind the scenes and exits when the done property is true.

for ( let n of [1,2,3] ) {
// 1
// 2
// 3

As long as the object implements the iterable interface it can be looped with the for of loop. This includes arrays, maps and sets.

var map = new Map();
map.set('a', 1);
map.set('b', 2);

for (let pair of map) {
// [a,1]
// [b,2]

Arrays, sets and maps also expose the entries, keys and values functions for returning specialised iterators. The keys iterator loops over only the keys, the values iterator only the values, and the entries iterator the key/value pairs.

var map = new Map();
map.set('a', 1);
map.set('b', 2);

for (let key of map.keys()) {
// a
// b

In ES6 strings also implement the iterable interface.

for (let char of 'foo') {
// 'f'
// 'o'
// 'o'

Posted on by:

mohananagavenkat profile

Mohana Naga Venkat Sayempu


Full-Stack Developer. In a relationship with web 😁. Worked for startup companies. Apart from that, I am a good Badminton Player.


markdown guide