JSBits #5: Loop statements: 'for..in' vs 'for..of'

Captain's log, stardate d73.y38/AB

Except for performance reasons (on very rare occasions), I always prefer "forEach" or "map" over "for" statements, but lately I'm programming in Angular, where it's common to use "for" loops in things like "ngFor".

Downwards staircase - Photo from Unsplash

So, again, there are two "for" statements in JavaScript to instruct loops. Yet another source of confusion, as per JavaScripts usual nature!

If you only have to know one thing is: try to avoid for loops… and then… always use "for..of" and never use "for..in".

I have always problems remembering this, so here's a mnemotechnic rule: "rof" is "for" backwards. "for…of" (the right choice) is almost a palindrome.

More information:

UPDATE: By the way, "for..of" is a ES6 feature, so I won't work in, sigh, some browsers. Check the compatibility table and transpile if necessary.

Daniel Gómez

Daniel Gómez

Dani started playing with computers with his Oric 1, at least 100 years ago. He now juggles his programming skills with two bands and being a father of three. Legend says, it's him and his identical twin brothers working as a team.

comments powered by Disqus

You're one step away from meeting your best partner in business.

Hire Us