Joined July 2011
·
Achievements
80 Karma
0 Total ProTip Views
Nephila Komaci
Have at least one original repos where PHP is the dominant language
Walrus
The walrus is no stranger to variety. Use at least 4 different languages throughout all your repos
Altruist
Increase developer well-being by sharing at least 20 open source projects
Forked
Have a project valued enough to be forked by someone else
Honey Badger 3
Have at least three Node.js specific repos
Raven
Have at least one original repo where some form of shell script is the dominant language
Honey Badger
Have at least one original Node.js-specific repo
Charity
Fork and commit to someone's open source project in need
One important thing to note here is this trick is useful for a lot of the array-like Objects that you might encounter in JavaScript. The two most common examples are the
arguments
variable inside a function body, and a NodeList, which is what gets returned from most DOM methods that return more than one DOM node. These array-like objects basically just have a .length property, and several sequential numerical keys indexed at "0" (remember, the keys of an Object are always strings). I suppose this harkens back to early JavaScript before a proper Array type even existed. It's funny how in most languages an Array is less complex than a hash/dictionary since they use integers as keys, but with JavaScript it's the complete opposite because of the way Objects are the base type and require strings as keys.Also, are you just using .map for terseness? Because in your last example you're creating an array full of undefineds and not assigning it anywhere. While it's probably trivial, I say use the right tool for the right job, and forEach is that tool, for only 4 keystrokes more. And while terseness is sometimes great, I can't see the logic in instantiating an Array just to get to Array.prototype.forEach or Array.prototype.map. Object caching optimizations still apply though, so if you use these function often, putting a
var forEach = Array.prototype.forEach.call
somewhere in your app will probably speed things up too.
Another trick that people tend to use is:
Array.prototype.slice.call(inputs)
which will coerce any array-like object (or basically any object with a .length property, even strings!) into a fully-fledged Array. This operation is slow, however, and nine times out of ten, the forEach.call or map.call is all what you want out of it anyway, and doing a for loop to iterate over it tends to be faster as well.