Javier Cabero Javier Cabero - 11 months ago 73
Javascript Question

Why using `Number.prototype.valueOf` inside of a `map()` without optional arg gives an error

Reading this question I tried to perform a modification to the code that creates an array filled with zeroes:

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

Instead of this, I wanted to use
and understand in a better way the usage of the
function in Javascript. Using the developer tools in Chrome I executed the following, getting an error:

Array.apply(null, Array(10)).fill(0).map(Number.prototype.valueOf);

Uncaught TypeError: Number.prototype.valueOf is not generic

As I understand the map function, it executes the callback on each value of the array using that value as argument. The array is correctly created using
Array.apply(null, Array(10)).fill(0)
, so it should be executing
, why is it giving then the error?


So it should be executing Number.prototype.valueOf(0), why is it giving then the error?

No. The map callback is called with no (undefined) this argument if you don't pass one to map, and the array element, the index, and the array as arguments. So it actually calls

Number.prototype.valueOf.call(undefined, 0, 0, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

But valueOf must be invoked on numbers or Number instances, otherwise it will throw.