for ... of loop

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

Expected output:

0 1 2

The advantages from the for…of loop are:

Support of for…of in other collections

Strings

for...of walks a string by Unicode code point, not by UTF-16 code unit. Each console.log prints one line:

const string = "abc";
for (const 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 (const name of uniqueNames) {
  console.log(name);
}

Expected output:

bob alejandro zandra anna

Maps

for...of also walks a Map. Each step yields a two-element array of key and 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]
}

Destructuring can name the key and the value:

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 does not walk a plain object's properties. Use for...in or Object.keys():

const someObject = { name: 'Mike' };

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

Expected output:

name: Mike

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents