Javascript for of loop in ES6

for…of loop is introduced in javascript ES6 version to iterate the elements of an iterable object.

It is used for iterating of an elements for

  • Strings
  • Array
  • Map
  • Set
  • User Defined Object

Syntax

for (javascriptvariable of iterableobject) {
  statement
}

javascriptvariable is an initial variable value declared with let or const, and var keyword iterable object is an array

Let’s see an examples of for of loop

  • array for of loop iteration

In this, Array contains numbers, each number is iterated with for of loop and assigned to variable. Inside the body,It is printed

var numbers=[1,2,3]
for(let i of numbers){
    console.log(i)
}

Output:

1
2
3

Another example, Sometimes, We want to use index with value for array iteration with for of loop.

Here is an example to get the index of an iteration in a for-of loop in JavaScript

var numbers=[11,12,13]
for(const [index,value] of numbers.entries()){
console.log(index +" : "+value)
}

Output:

0 : 11
1 : 12
2 : 13
  • String for of loop

Here is an for loop with string and index example

var numbers=["one","two","three"]
for(const [index,value] of numbers.entries()){
  console.log(index +" : "+value)
}

Output:

0 : one
1 : two
2 : three