JavaScript Loop For Of
JavaScript Basics

JavaScript Loop For Of

The For Of Loop

The JavaScript for of statement loops through the values of an iterable object. It allows you to iterate over data structures like Arrays, Strings, Maps, NodeLists, and more.

Syntax

for (variable of iterable) {  // code block to be executed}

  • variable: For each iteration, the value of the next property is assigned to the variable. The variable can be declared with const, let, or var.
  • iterable: An object that has iterable properties.

Browser Support

The for of loop was added to JavaScript in 2015 (ES6). It is supported in:

  • Chrome 38 (Oct 2014)
  • Edge 12 (Jul 2015)
  • Firefox 51 (Oct 2016)
  • Safari 7 (Oct 2013)
  • Opera 25 (Oct 2014)

Note: for of is not supported in Internet Explorer.

Looping Over an Array

Example

const fruits = ["Apple", "Banana", "Cherry"];‍let result = "";for (let fruit of fruits) {  result += fruit + " ";}‍

In this example, result will be "Apple Banana Cherry ".

Looping Over a String

Example

let greeting = "Hello";‍let result = "";for (let char of greeting) {  result += char + " ";}

In this example, result will be "H e l l o ".

The While Loop

The while loop and the do/while loop will be explained in the next chapter.

Take a look into your desired course