JavaScript : For Of

In JavaScript, the `for...of` loop is used to iterate over the elements of an iterable object, such as arrays, strings, maps, sets, and more. It provides a concise and readable way to loop through the elements without needing to deal with index values or keys. Here's the syntax of the `for...of` loop:

Syntax:


for (variable of iterable) {
  // Code block to be executed
}

  • variable: A variable that represents the current element in the iteration.
  • iterable: The iterable object being looped over, such as an array, string, map, set, etc.

Example with Array:


const fruits = ['apple', 'banana', 'orange'];

for (let fruit of fruits) {
  console.log(fruit);
}

 

Output:


apple
banana
orange

 

Example with String:


const message = 'Hello';

for (let char of message) {
  console.log(char);
}

 

Output:

H
e
l
l
o

 

Notes:

 

  • The for...of loop iterates over the elements of an iterable object in the order of insertion or defined order.
  • It provides a simpler alternative to the for...in loop when you don't need to iterate over object keys or indices.
  • It works with any object that implements the iterable protocol, including arrays, strings, maps, sets, and custom iterable objects.
  • The loop variable variable holds the value of each element in the iterable, rather than the index or key.

Example with Map:


const map = new Map([
  ['name', 'John'],
  ['age', 30]
]);

for (let [key, value] of map) {
  console.log(key + ': ' + value);
}

 

Output:

name: John
age: 30

 

The for...of loop simplifies the process of iterating over elements in iterable objects, making your code cleaner and more expressive. It's a powerful feature introduced in ECMAScript 6 (ES6) and is widely used in modern JavaScript development.