ES6 - for of statement

ES6 JavaScript

In this ES6 tutorial we are going to learn about for...of statement.

What is for...of statement?

We use for...of statement to iterate over iterables like Array, String, Set etc.

Using for...of to iterate over array

Let's say we have an array having 5 elements and we want to print them. There are couple of ways we can solve this. We can use the for loop. We can use forEach method and we can achieve the same result using for...of statement.

Here is the code to iterate an array using for...of statement.

const arr = [1,2,3,4,5];
for(const element of arr) {
  console.log(element);
}

Using for...of to iterate over string

Let's say we have a string and we want to print all the characters of the string. We can achieve this using the for loop like the following.

const str = 'Hello';
for(let i = 0; i < str.length; i++) {
  console.log(str[i]);
}

We can solve this using the for...of statement like the following.

const str = 'Hello';
for(const ch of str) {
  console.log(ch);
}

Alright this brings us to the end of this tutorial. Don't forget to practice the examples. See you in the next tutorial.