Jeremy Iglehart Jeremy Iglehart - 4 months ago 7
Javascript Question

Why do we use `Number.prototype.valueOf` inside of a `map()` function

The following code:

let resultsArray = Array.apply(null, Array(10)).map(Number.prototype.valueOf,0);

creates the following array

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Why does map() need
just to push the number 0 in to each position of this array. Is there a different way to achieve this result, or is this the best way?


In your code, 0 is passed to Number.prototype.valueOf which just returns the primitive (0).

Which is essentially the same thing as

If your code was:

let resultsArray = Array.apply(null, Array(10)).map(Number.prototype.valueOf,10);

The map() function would essentially be calling Number.prototype.valueOf like this:

Here's the documentation - which provides a nice Polyfill that you can read and see exactly what map() is doing.

But surely you can do it in a more tricky way ;)

var resultsArray = '0'.repeat(10).split('').map(Number);