Javascript for of vs for in vs for each

If you are new to Javascript (or even a seasoned js developer), you will probably get confused when trying to understand the different types of for loops. So let’s go through the javascript for of vs for in vs for each loop.

Standard for loop

Suppose we have an array called myArray. Here’s how you would iterate through it using the standard for loop:

var myArray = ['Cat','Dog','Horse'];
 
for(let i =0; i< myArray.length;i+=1){
console.log(myArray[i]);
}

No surprise here, this is pretty much standard across all programming languages. This is also (questionably) that fastest way to iterate through. Your output would be:

Cat

Dog

Horse

for each

If you want to get fancy with shortcuts or you simply like to follow the Airbnb coding style guide, then you can use the for-each loop. It executes the provided function (or arrow function) for each item in the array:

myArray.forEach((element)=>{
console.log(element);
})

The output would be the same as above.

for of

Another way to iterate over any iterable object is using for of. Using for of allows you to also iterate through each character in a string or entry in a map. Here’s what it looks like using our previous array:

for(let i of myArray){
console.log(i)
}

The output would be the same as the other two.

for in

This is the one that always confuses everybody. Unlike the previous loops, for in works a little differently. It iterates over the enumerable properties or keys of an object or array. So in this case, if we used for in we get the following:

for(let i in myArray){
console.log(i);
}

Our output would be:

0

1

2

For in is mostly useful if you want to iterate through an object’s keys. Say I have the following:

var myobj = {first:'Dave',last:'Bennett', birth:''}

for(let i in myobj){
if(!myobj[i]){
console.log(`Missing ${i}`)
}
}

It goes through all of the object’s properties to see if any are blank. If they are, it prints out which property is blank.

So there’s all you need to know to get started with the different javascript for of vs for in vs for each.