for of

Understanding the For Of Loop in JavaScript

As a programmer, it's important to know how to effectively loop through arrays and objects in JavaScript. One way to do this is by using the "for of" loop.

Syntax:


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

The "for of" loop allows you to iterate over arrays, strings, and other iterable objects. The loop will execute for each element in the iterable object.

Example:


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

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

In this example, we create an array of fruits and then use the "for of" loop to iterate over each fruit in the array. The loop will execute three times, once for each fruit in the array, and will output "apple", "banana", and "orange" to the console.

Multiple Ways to Use:

  • You can use the "for of" loop with a string:

  const myString = "hello";

  for (let char of myString) {
    console.log(char);
  }
  
  • You can use the "for of" loop with other iterable objects:

  const mySet = new Set([1, 2, 3]);

  for (let item of mySet) {
    console.log(item);
  }
  
  • You can also destructure an array within a for-of loop:

  const myArray = [[1, 2], [3, 4], [5, 6]];

  for (let [a, b] of myArray) {
    console.log(a, b);
  }
  

Overall, the "for of" loop is a useful tool for iterating through arrays, strings, and other iterable objects in JavaScript. It can be used in multiple ways to accomplish various tasks.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe