for..of-in-ECMA6

This repository contains a small discussion on for..of loops in ECMA6.

View on GitHub

for..of loop in ECMA6

In ECMA6, we have a for..of loop which loops over the iterable objects such as String, Arrays, Collections(Map, Set) etc.

Before we talk about for..of loop, let’s remember our companion from ECMA5 days i.e. for..in loop. for..in loop is used to loop over the indexes in an array/keys in case of objects.

var fruits = ["Banana", "Orange", "Kiwi", "Apple"];
for (var index in fruits) {
  console.log(index);
}

Output: 0 1 2 3

But, for..of loop is to loop over values in an array or any iterable object for that matter.

Below is the basic syntax of a for..of loop:

for (let value of iterable)

Let’s see for..of loop in action with a few iterables:

Array

let fruits = ["Banana", "Orange", "Kiwi", "Apple"];
for (let fruit of fruits) {
  console.log(fruit);
}

Output : Banana Orange Kiwi Apple

String

let city = "Berlin";
for (let char of city) {
  console.log(char)
}

Output : B e r l i n

Map

let map = new Map();
map.set(0, 'Zero');
map.set(1, 'One');
for (let element of map) {
  console.log(element);
}

Output : [ 0, 'Zero' ] [ 1, 'One' ]

In case you want to get the value in the key/value pair in a Map, you can do following:

for (let [key, value] of map) {
  console.log(value);
}

Output: Zero One

arguments In case you want to loop over the arguments of a function, you can do the following:

function() {
  for (let argument of arguments) {
    console.log(argument);
  }
})(1, 2, 3, 4)

Output: 1 2 3 4

So, if we try to compare for..in loop with for..of loop, they are different in the below ways:

An important point to note about for..in loop is that it gives us index/keys which are of type string which cannot always be helpful. Also fixing this behaviour could have caused breaking changes at many other places, so that is another reason to introduce new for..of loop.

One thing which is extremely important to note here is that the value you want to loop over should be an iterable object.

A working demo is available here.

Follow Me

Github

Twitter

LinkedIn

More Blogs By Me