Contents
After years of web development, do you still find yourself mixing up for...in
and for...of
loops in JavaScript? If you’re tired of Googling every time you need to loop through a collection, I’ve got a handy memory trick to help you effortlessly remember when to use each loop statement.
a) “index in, object of”
b) ‘i’n -> not ‘i’terables, o’f -> not ‘o’bjects
for…in loops over enumerable property names of an object.
for…of (new in ES6) does use an object-specific iterator and loops over the values generated by that.
Code Snippet:
|
|
Almost everytime I expect that value of colors will be printed instead of index values. To get the values we have to modify the loop as below
|
|
Using for...of
loop
|
|
Difference
for...in | for...of | |
---|---|---|
Applies to | Enumerable Properties | Iterable Collections |
Use with Objects? | Yes | No |
Use with Arrays? | Yes, but not advised | Yes |
Use with Strings? | Yes, but not advised | Yes |
I will not go much into the differences; you can read the blog JavaScript for…of vs for…in Loops (A Complete Guide)
However, I prefer to use for...of
almost everywhere. Infact for looping over properties of an object too; I prefer for...of
loop like below:
|
|
Conclusion:
In this post, I have not dived much deep into the differences. I prefer to use for...of
loop almost everytime. Another big advantage of preferring for...of
loop is early exiting.
✨ Thank you for reading and I hope you find it helpful. I sincerely request for your feedback in the comment’s section.