JavaScript For Of

By | August 25, 2022

The For Of Loop

The JavaScript for of statement loops through the values of an iterable object.

It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more:

Syntax

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

variable – For every iteration the value of the next property is assigned to the variable. Variable can be declared with constlet, or var.

iterable – An object that has iterable properties.

Browser Support

For/of was added to JavaScript in 2015 (ES6)

Safari 7 was the first browser to support for of:

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

For/of is not supported in Internet Explorer.

Looping over an Array

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The for of statement loops through the values of any iterable object:</p>
<p id="demo"></p>
<script>
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
  text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Result:

JavaScript For Of Loop

The for of statement loops through the values of any iterable object:

BMW
Volvo
Mini

Looping over a String

Example

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The for of statement loops through the values of an iterable object.</p>
<p id="demo"></p>
<script>
let language = "JavaScript";
let text = "";
for (let x of language) {
  text += x + "<br>";
}​
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Result:

JavaScript For Of Loop

The for of statement loops through the values of an iterable object.

J
a
v
a
S
c
r
i
p
t

Leave a Reply

Your email address will not be published. Required fields are marked *