After years of web development, do you still find yourself mixing up
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.
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
|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|
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:
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.