DEV Community

Max
Max

Posted on

JavaScript for of loop tutorial

In JavaScript, the for of loop is another way of iterating over an iterable object like an array, string, or set. It was introduced in ES6 and offers an alternative to the traditional for loop and for...in loop.

Syntax for a for of loop

for (let value of iterable) {
  // code block
}
Enter fullscreen mode Exit fullscreen mode

Here, value is a variable that takes the value of the element in each iteration of the loop, and iterable is an object that has iterable properties, such as an array or a string.

for of loop Iterate over array

Iterating over an Array Let's start with an example of how to use the for...of loop to iterate over an array:

const numbers = ['one', 'two', 'three'];

for (let number of numbers) {
  console.log(number);
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have an array of numbers, and we use the for of loop to iterate over each element of the array and log it to the console.

Output

one
two
three
Enter fullscreen mode Exit fullscreen mode

for of loop Iterate over string

Iterating over a String You can also use the for of loop to iterate over a string

const hello = 'Hello World';

for (let chr of hello) {
  console.log(chr);
}
Enter fullscreen mode Exit fullscreen mode

We use the for of loop to iterate over each character in the string and log it to the console.

Output

H
e
l
l
o

W
o
r
l
d
Enter fullscreen mode Exit fullscreen mode

for of loop Iterate over Map

Iterating over a Map The for of loop can also be used to iterate over a Map object

const numbers = new Map([
  ['One', 1],
  ['Two', 2],
  ['Three', 3]
]);

for (let [word, number] of numbers) {
  console.log(`word: ${word} number: ${number}`);
}
Enter fullscreen mode Exit fullscreen mode

Output

word: One number: 1
word: Two number: 2
word: Three number: 3
Enter fullscreen mode Exit fullscreen mode

Learn JavaScript tutorial

Top comments (0)