Volver

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

Diario del capitán, fecha estelar d73.y38/AB

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

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".

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.

Compartir este post

Artículos relacionados

JSBits #3: 10 things to remember

JSBits #3: 10 things to remember

Here's another JavaScript bits we wanted to share with you. 10 things to remember when coding.

Leer el artículo
JSBits #4: Comparison operator

JSBits #4: Comparison operator

Here's another JavaScript bits we wanted to share with you. Let's talk about the comparison operator, today.

Leer el artículo
JSBits #6: Lerna vs. Yarn workspaces

JSBits #6: Lerna vs. Yarn workspaces

Here's another JavaScript bits we wanted to share with you. Let's talk about Lerna vs. Yarn workspaces, today.

Leer el artículo