DEV Community 👩‍💻👨‍💻

Mayank Arya
Mayank Arya

Posted on

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





Top comments (0)

New programmer and javascript

Stop by this week's meme thread!