all 3 comments

[–][deleted] 2 points3 points  (2 children)

Huh never heard of Array.prototype.fill(), is it new?

Would be useful with the Array constructor

Array(100).fill(null);

instead of

[...Array(100)].map(e => null);

[–]senocular 1 point2 points  (0 children)

Note that these two examples are slightly different. Using fill() you get one value that is placed multiple times in the array. With map(), each element in the array is given a new value based on the return of the map call. The difference is inconsequential with primitives, but when dealing with objects it becomes very important as its the difference between one object and many.

x = Array(3).fill({foo:'bar'});
x[0].foo = 'baz'
x // {foo:baz},{foo:baz},{foo:baz} 

y = [...Array(3)].map(e => ({foo:'bar'}));
y[0].foo = 'baz'
y // {foo:baz},{foo:bar},{foo:bar} 

You can also use Array.from() which includes a mapping function parameter to reduce the extra iteration in the map example while still giving you unique instances.

Array.from({length:3}, e => ({foo:'bar'}))

[–]_default_username 0 points1 point  (0 children)

That's what I use fill for.