Hacker News new | past | comments | ask | show | jobs | submit login

for...of isn't only for arrays. Anything that implements the Symbol.iterator functionality can use for..of, which is pretty nifty for some custom classes and also includes things like the new Map and Set collections, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

However, even in just arrays there is arguably a benefit. Namely, an extra function being created and invoked with forEach. While in a JITing compiler, the performance difference between for...of and forEach might be negligible (or non existent), you can't always be sure what the JIT is going to do. For hotspots, I would probably prefer for..of




If you're not in a JIT, for-of performance is going to be terrible too. Instead of creating a single function (which may not happen _anyway_ in the non-jit case, depending on how it's implemented) you now have to create an iterator result object for every single thing you get out of the iterator.

In a JIT, forEach is actually _easier_ to optimize well (just need to inline the callback function, though of course that can fail for various reasons) than for-of (need to inline the calls to next() on the iterator, need to do escape analysis on the return value of next(), need to do scalar replacement on the return value of next; note that this is a strict superset of the work needed to optimize forEach).

for-of can be nicer to read, and can work on arbitrary iterables. Those are its key strengths. Performance just isn't, unfortunately.


Ah, you're actually answering my question from above. I was wondering if there was a way to emulate the behaviour I've gotten accustomed to in Ruby vis à vis `Enumerable#each` where the (key, value) are yielded to the block passed to each. It doesn't seem to be possible to do that with object literals in JS, but you mention that Map would do (and it actually does, see [1]). Nice.

[1] https://developer.mozilla.org/en/docs/Web/JavaScript/Referen...




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: