Hacker News new | ask | show | jobs
by lomnakkus 4180 days ago
Just looking at your example:

    for (var i = 0; i < y.length; i++) { ... }
    for (var x in y) { ... }
    for (var x of y) { ... }
    y.forEach(function(x, i) { ... })
    Object.keys(y).forEach(function(x) { ... })
None of the "for" variations are considered good practice in ES6. You should be using "let" (or "const" if it's allowed here) to avoid var-hoisting of "i".

Personally, I'd advocate using "for" if you have a need for early return/break/continue -- otherwise I'd go for the first forEach() variant. Or, even better, use "map" and avoid side effects in the function you're mapping over the collection. Unless of course you're doing something imperative.

The fact that the last forEach() variant is possible is a good thing, though I wouldn't recommend its use in this case because it's needlessly complex -- it shows that the language/stdlib is becoming more compositional.

1 comments

Yes, "let" is better than "var". I could also have used a fat arrow in the forEach(). But my point was to list iteration variations, so outside of that I wrote traditional ES5.

This illustrates the issue though. "var" is like "let" but without block scoping, so you should almost never use "var", but it's still there to trip newcomers. The fat arrow is like the "function" keyword and most of the time you can use them interchangeably, but if you rely on "this" they're not interchangeable anymore.

This growing laundry list isn't exactly thrilling. I'm glad to have map(), filter(), every() and friends, though.

Have a pre-commit linter disallow "var". (etc. for everything else.)

In a language like JS you cannot have it all, but at least appreciate the improvements! ;)