re: Useful JS functions you aren't using: VIEW POST


Another addition is that methods like map (and also forEach, every...) do not iterate over empty items. For example: new Array(5).forEach(console.log) doesn't print anything, so beware!

Note: it doesn't mean they don't iterate over undefined values. Just empty, pristine slots that hasn't been assigned a value yet.

So if you're thinking you could use new Array(n).forEach(fn) to execute fn n times, you're out of luck. Also, that would generate a throwaway array, so it's sub-optimal. Use for for that.

(There's also this trick: Array.from({ length: 3 }).forEach(console.log). It works, but it's kind of jarring. Again, I don't recommend doing that.)

Others already pointed out that map returns a new array. Good for immutability!

code of conduct - report abuse