Definition and Usage
The for...of
statement is a loop designed for objects iterable by value.
Any object iterable by value can be traversed using for...of
. In other words, it runs a loop that operates on the values retrieved from the object.
Objects iterable by value include the following:
- Arrays, strings, Map, Set, and other objects with Iteration Protocols applied
HTMLCollection
andNodeList
objects, which are DOM collections- Certain array-like objects such as
arguments
- User-defined objects with Iteration Protocols applied
In the past, arrays, objects, strings, and other types each required different looping methods. The for...of
statement resolves this inconsistency, providing a single loop that can be applied to any object iterable by value.
Note:
Plain objects, such as those created with object literals, cannot be iterated by value.
Instead of using for...of
, you can loop through their properties (keys) with for...in
.
Basic Example
Here is an example of using the for...of
statement to loop through a representative array object iterable by value.
const iterable = [1, 2, 3, 4, 5]; // Using an array as an example
for (const item of iterable) {
console.log(item);
}
1 2 3 4 5
Syntax
for (variable of iterable) {
// code to execute for each iteration
}
variable
: The name of the variable that stores the current value being iterated over.iterable
: The object iterable by value that you want to loop through.
Practical Examples – Iterating Different Objects
Here are examples of using the for...of
statement to loop through various objects iterable by value.
Array
const arr = ["apple", "banana", "cherry"];
for (const fruit of arr) {
console.log(fruit);
}
// Output: "apple" "banana" "cherry"
String
const str = "abc";
for (const char of str) {
console.log(char);
}
// Output: "a" "b" "c"
Map
const map = new Map([["key1", "value1"], ["key2", "value2"]]);
for (const [key, value] of map) {
console.log(key, value);
}
// Output: "key1 value1" "key2 value2"
Set
const set = new Set([1, 2, 3]);
for (const value of set) {
console.log(value);
}
// Output: 1 2 3
HTMLCollection
<ul>
<li>Sushi</li>
<li>Ramen</li>
<li>Tacos</li>
</ul>
// Selecting all <li> elements
const liElements = document.getElementsByTagName("li");
console.log(liElements); // HTMLCollection(3) [li, li, li]
// Using for...of
for (const liElement of liElements) {
console.log(liElement.textContent);
}
// Output: "Sushi" "Ramen" "Tacos"
NodeList
<ul>
<li>Sushi</li>
<li>Ramen</li>
<li>Tacos</li>
</ul>
// Selecting all <li> elements using querySelectorAll
const liElements = document.querySelectorAll("li");
console.log(liElements); // NodeList(3) [li, li, li]
// Using for...of
for (const liElement of liElements) {
console.log(liElement.textContent);
}
// Output: "Sushi" "Ramen" "Tacos"
Code Explanation
The NodeList
object returned by querySelectorAll()
is an array-like object that implements the Iteration Protocols, making it iterable by value.
arguments
function showArgs() {
for (const arg of arguments) {
console.log(arg);
}
}
showArgs(10, 20, 30);
// Output: 10 20 30
Using break
and continue
You can use break
and continue
statements to control the loop in a for...of
statement. The following examples show how to exit or skip iterations based on conditions.
// break example: exit the loop if the number is 3 or greater
const numbers = [1, 2, 3, 4, 5];
for (const num of numbers) {
if (num >= 3) break;
console.log(num);
}
// Output: 1 2
// continue example: skip the number 3
for (const num of numbers) {
if (num === 3) continue;
console.log(num);
}
// Output: 1 2 4 5
Important Notes
The for...of
statement is a loop designed for objects iterable by value. In other words, it runs a loop on the values retrieved from an object. This provides convenience, but there are some limitations. Being aware of them can help avoid unnecessary errors or confusion.
Cannot Access Index Directly
The for...of
statement only provides the current value being iterated. It does not provide the index directly.
const numbers = [10, 20, 30];
// Iterates over values only
for (const value of numbers) {
console.log(value); // 10, 20, 30
}
Cannot Use on Plain Objects
Plain objects, such as those created with object literals, cannot be iterated by value. Instead of using for...of
, you can loop through their properties (keys) with for...in
.
const obj = {
a: 1,
b: 2
}
// This will throw an error!
for (const value of obj) {
console.log(value);
}
// TypeError: obj is not iterable
To iterate over a plain object using for...of
, you can use methods such as Object.keys()
, Object.values()
, or Object.entries()
.
const obj = {
a: 1,
b: 2
}
// Loop over keys
for (const key of Object.keys(obj)) {
console.log(key); // a, b
}
// Loop over values
for (const value of Object.values(obj)) {
console.log(value); // 1, 2
}
// Loop over both keys and values
for (const [key, value] of Object.entries(obj)) {
console.log(key, value); // a 1, b 2
}
Specifications
Specification | |
---|---|
for...of
|
ECMAScript Language Specification #sec-for-in-and-for-of-statements |
Compatibility
Statement |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
Node.js
|
---|---|---|---|---|---|
for...of
|
38 | 12 | 13 | 7 | 0.12 |