Jeremy Iglehart Jeremy Iglehart - 5 months ago 11
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
Number.prototype.valueOf
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?

Answer

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

Which is essentially the same thing as

Number.prototype.valueOf.call(0)

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:

Number.prototype.valueOf.call(10)

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);
console.log(resultsArray);