JavaScript for of loop tutorial
Max
Posted on April 29, 2023
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
}
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);
}
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
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);
}
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
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}`);
}
Output
word: One number: 1
word: Two number: 2
word: Three number: 3
Posted on April 29, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.