DEV Community

Mayank Arya
Mayank Arya

Posted on

2

for-in and for-of with arrays.

So in the beginning of my career I was working for a project where I had to deal with a lot of arrays and objects. Also there was a requirement of an asynchronous task within the loop!
On taking up the task I was like, "Eh, I'm going to complete this thing in no time and then watch an episode ;-)".

for () { await *db_call* }

But then as soon as I finished up writing my code, I tested it (just the response as I was too confident of the logic and implementation) and was surprised to see "undefined undefined undefined.....".

Now "How to do an asynchronous task in a loop?" is a separate post. Here I will talk about how I approached looping.

JavaScript has way too many methods to loop and doing asynchronous tasks within each one has a different level of difficulty but since this post is for beginners, the most basic loop is the for loop.
Yup, talking about the omnipresent for(var i = 0; i<limit; i++){}.
If we are talking about ES6, we also get very basic and easy to use (with easy to do async tasks facility) for-in and for-of loops.

What I learned is what I am going to share with you in the simplest way possible.

Syntax: for(let item in array){} -> item will hold index of arrays
Syntax: for(let item of array){} -> item will hold element of arrays

Therefore, we can also call them as:

for-in ->

for(let index in array)
{
// body
}

for-of ->

for(let element of array)
{
// body
}

Example:

for-in

Example:

for-of

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay