JavaScript for…of Loop
Last Updated :
04 Mar, 2024
JavaScript for...of
loop is used to iterate over iterable objects such as arrays, strings, maps, sets, etc. It provides a simpler syntax compared to traditional for
loops.
Syntax:
for ( variable of iterableObjectName) {
// code block to be executed
}
Parameters:
- Variable: Represents the current value of each iteration from the iterable.
- Iterable: Any object that can be iterated over (e.g., arrays, strings, maps).
Example:
Here, we are looping over an array.
Javascript
const array = [1, 2, 3, 4, 5];
for (const item of array) {
console.log(item);
}
|
Explanation:
The code initializes an array with values 1 through 5. It then iterates over each element of the array using a for…of loop, logging each element to the console.
Example:
Here, we are looping over an String.
Javascript
const str = "Hello" ;
for (const char of str) {
console.log(char);
}
|
Explanation:
Here,
str
is the string you want to loop over.
for (const char of str)
initiates the for...of
loop, where char
represents each character in the string during each iteration.
console.log(char)
prints each character to the console during each iteration of the loop.
for…of Loop Example – Looping over Map
Here, we are looping over an Map.
Javascript
const map = new Map([
[ 'key1' , 'value1' ],
[ 'key2' , 'value2' ],
[ 'key3' , 'value3' ]
]);
for (const [key, value] of map) {
console.log(`Key: ${key}, Value: ${value}`);
}
|
Output
Key: key1, Value: value1
Key: key2, Value: value2
Key: key3, Value: value3
Explanation:
Here,
map
is the Map object you want to iterate over.
for (const [key, value] of map)
initiates the for...of
loop, where [key, value]
represents each key-value pair in the Map during each iteration.
- Inside the loop,
console.log(
Key: ${key}, Value: ${value});
prints each key-value pair to the console during each iteration of the loop.
Share your thoughts in the comments
Please Login to comment...