What is for...of in JavaScript?

The for...of function in JavaScript is used to iterate over iterable objects of provided value. These values can be Array, Set, String, Maps, TypedArray, or array-like objects (like arguments, such as Nodelist).

Basic example

The following code iterates over the items in the array and displays each item value in it.

const test = ['1', '2', '3', '4', '5'];
for (const item of test) {
console.log(item);
}

Iterating over an array

As we have seen earlier, the for...of function allows us to iterate over arrays. We can also manipulate the value of the item from each iteration before it goes through the output.

const test = [2, 4, 6];
for (let item of test) {
item += 2;
console.log(item);
}

In the code above, we iterated over the value of the array. Then, we added the number two to each item in the array before actually displaying it.

Iterating over a string

We can also iterate over strings. The following code goes through each letter in the string and displays it.

const test = "Educative";
for (let item of test) {
console.log(item);
}

Iterating over a set

It can also iterate over sets. In the example below, we create a new Set from an array with duplicate values:

const test = new Set([2, 4, 6, 8, 2, 8,10]);
for (let item of test) {
console.log(item);
}

Even though we initialized the array with duplicate values, the results only show unique array items. The reason is that the test is now a Set and has been stripped of all duplicate values.

You can find more details about for..of here.

Free Resources