Skip to content
the poor coder

for of

Poor Man
Published
Reading time
1 min read
On this page

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:#

Text

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:#

Text

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:
Text

  const myString = "hello";

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

  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:
Text

  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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC