for..of loop in ECMA6

of loop which loops over the iterable objects such as String, Arrays, Collections(Map, Set) etc.

in loop is used to loop over the indexes in an array/keys in case of objects.

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

of loop in action with a few iterables: – – In case you want to get the value in the key/value pair in a Map, you can do following: – – arguments In case you want to loop over the arguments of a function, you can do the following: -…

of loop, we can loop over the values of any iterable object such as String, Arrays, Collections.

This repository contains a small discussion on for..of loops 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.

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:

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

Array

String

Map

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

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

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

Using for..in loop, we can loop over the keys of an Object. for..in loop is not recommended for Arrays as the purpose of for..in loop is to enumerate over object properties, which means that it will also be enumerating over inherited properties which isn’t always desired. Also order of iteration is not guaranteed. One of the sample is given below: