Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
programming
loop
communitycreator
for

What is for...of in JavaScript?

Chibuike Nwachukwu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
}
Running basic example

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);
}
Iterating over an array

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 string

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);
}
Iterating over a set

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.

RELATED TAGS

javascript
programming
loop
communitycreator
for

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring