JavaScript for…of Loop in ES6

Tram Ho

In this tutorial, I will introduce you to the for … of statement in js that allows you to loop through an iterable object.

ES6 introduced a new structure for … of that creates a loop over iterable objects such as Array , Map , Set or any other iterable object.

Below is an example for … of

Let’s see some examples of using for … of

Array

The following example shows you how to use for … of to loop through the elements of an array

If you don’t change the variable inside the loop, you should use const instead of let like so:

String

The following example shows you how to use for … of to loop through the elements of a string

Map

The following example shows you how to use for … of to loop through the elements of a map

Set

The following example shows you how to use for … of to loop through the elements of a set

for … of vs. for … in

The for … in loop loops through all the enumerable properties of an object. It is not iterated over a set such as Array , Map , Set

Unlike for … in loops, for … of loops iterate over a set, instead of an object. In fact, for … of iterates over the elements of any set with the [Symbol.iterator] attribute.

The following example illustrates the difference between for … of and for … in

In this article, I have used for … of in js to loop through a collection

See you in the next article

Share the news now

Source : Viblo