DEV Community

Cover image for Loop over iterable and object with for..in and for..of
Dev Duckling
Dev Duckling

Posted on

Loop over iterable and object with for..in and for..of

In the world of loops, there are for..of and for..in statements that I'm going to discuss.
for..of is mostly used to loop over arrays, strings, map,..etc.

Syntax:
for(items of array){
console.log(items);
} 
Enter fullscreen mode Exit fullscreen mode

Let's understand for..of
I used names from anime Demon Slayer in below examples. This is my first time embedding pen into blog and it is not showing console, meh.

So if you look at the code I have made an array named Japan just for making code more readable. Goal is to access the hashiras from nested array. For loop can be used but it is not readable like for..of.


for..in is used to loop over objects. You can use for..of too with slight adjustment.

Syntax:
for(key in object){
console.log(key);
} 
Enter fullscreen mode Exit fullscreen mode


Have a look at the code maybe visit pen if possible as console is not showing up. In the above pen I have made object demonSlayer. Goal is to use for..in and get key and value from the object, which is in the console.

You cannot iterate over object as for..of won't work but it is possible to select object's key or value and iterate over them by method Object.value and Object.key, fork above pen and try below code

for(hashirasElements of Object.keys(demonSlayer)){
console.log(hashirasElements);
}

for(hashirasNames of Object.values(demonSlayer)){
console.log(hashirasNames);
}

Enter fullscreen mode Exit fullscreen mode

The above code would give you keys and values from our object using for..of.
That's it! Thanks for reading this blog!

Top comments (0)