javascript

For-of Loop

For of loop is one of a few recent additions to the for loop in JavaScript. It makes it possible to do what is basically a foreach in most other programming languages, like for example C#.
for(var item of array){} is more or less the same as foreach(var item in array){} in C#.
Why not just use .map or .forEach? Well, I usually do, but to do that can be a little bit cumbersome when you are dealing with async methods and async await, because then the arrow function in the .map also needs to be async etc.
And it is nice to have a fast way to just loop through an array without having use an old school for loops. They are useful sometimes, and you should know how they work, but it is nice to have a quick and easy way to just loop through an array.

var myArray = [1,2,3,4,5]
for(let item of myArray){
  console.log(item)
}

 

Leave a Reply