How to Use the for…of Statement in JavaScript



In this article, you will learn 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;