How to Use the for…of Statement in JavaScript

02/05/2022

Contents

In this article, I will introduce how to use the for…of statement in JavaScript.

The for…of statement in JavaScript

An object that contains multiple elements such as an array is called an iterable object.
The iterable object also contains a string.

The JavaScript for-of statement creates a loop iterating over iterable objects.

The syntax is below.

for (variable of iterable) {
  // do something
}

Please note that it works on most browsers such as Chrome, but not on some browsers such as Internet Explorer.

Sample Code

Below is sample code that retrieves an element from an array using a for-of statement.

let fruits = ["apple", "orange", "grape", "lemon"];

for(let fruit of fruits){
  let flg = true;
  let str = "";
  for(let ch of fruit) {
    str += flg ? ch.toUpperCase() : ch;
    flg = !flg;
  }
  console.log(str);
}