JavaScript Tutorial JavaScript References

JavaScript - For Of Loop



JavaScript For Of Loop

The for...of statement is used to create a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.

Syntax

for(variable of iterable){
  statements;
} 

On each iteration, one property from iterable is assigned to variable and executes the given code statements. The loop continues doing the same till all properties of the object are exhausted. The variable may be declared with const, let, or var.

For Of Loop over an Array

In the example below, the for of loop is used to iterate over an array. It is used to print array elements.

var Arr = [10, 20, 30, 40, 50];
var txt = "";

for (var i of Arr) 
  txt = txt + i + "<br>";  

The output (value of txt) after running above script will be:

10
20
30
40
50

For Of Loop over a String

Similarly, the for of loop can be used with a string.

var str = "Hello";
var txt = "";

for (var i of str) 
  txt = txt + i + "<br>";  

The output (value of txt) after running above script will be:

H
e
l
l
o

For Of Loop over a Map

Consider the example below, where the for of loop is used with a map.

var MyMap = new Map([[1, "MON"], 
                     [2, "TUE"], 
                     [3, "WED"],
                     [4, "THU"],
                     [5, "FRI"]]);
var txt = "";

for (var [key, value] of MyMap) 
  txt = txt + key + " = " + value + "<br>";  

The output (value of txt) after running above script will be:

1 = MON
2 = TUE
3 = WED
4 = THU
5 = FRI

5