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 fnn 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!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Another addition is that methods like
map
(and alsoforEach
,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 executefn
n
times, you're out of luck. Also, that would generate a throwaway array, so it's sub-optimal. Usefor
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!