Open In App

JavaScript for…of Loop

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:



Example:

Here, we are looping over an array.




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

Output

1
2
3
4
5

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.




const str = "Hello";
 
for (const char of str) {
  console.log(char);
}

Output
H
e
l
l
o

Explanation:

Here,

for…of Loop Example – Looping over Map

Here, we are looping over an Map.




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,


Article Tags :