How can I figure out the behavior of call and bind on a javascript built in function

Viewed 40

I was trying to understand this code. Array(8).fill(0).map(Number.call, Number). The problem is that the behavior of this is very hard to understand because there is no way to see the implementation of number. If you try to .toString Number it will just say "native code". This is also true for using bind and call with the built in functions. How can I found out how this should behave?

1 Answers

If you want to know how Number works in detail, take a look at its ECMAScript specs.

If you want to know how Number works in general, take a look at its MDN documentation.

Basically, all Number(value) does is to convert value into a number type. Nothing else.

I believe what you need to understand to understand this code is actually about Function.prototype.call instead of Number.

When we translate the above code into a less fancy one, we get something roughly like this (this is important for explanation below):

console.log(
  Array(8).fill(0).map(Function.prototype.call, Number)
);

Now, in .map, it receives 2 arguments:

  1. Callback, with 3 arguments: currentValue, currentIndex, originalArray.
  2. Custom this value

So what the above code does is passing Number.call as the callback, and Number as the custom this value.

If you understand .call method, you'll know it must receive at least 1 arguments:

  1. this value.
  2. ...Argument n

Knowing all these, we can now translate the code above to even less fancy one:

console.log(
  Array(8).fill(0).map(function(currentValue, currentIndex, originalArray){
    return this.call(currentValue, currentIndex);
  }, Number)
);

This can be translated to even less fancy one too:

console.log(
  // Making `currentValue` into `_` because its existence does not matter in this case
  Array(8).fill(0).map(function(_, currentIndex){
    return Number.call(_, currentIndex);
  })
);

Now, the final translation, which is the most understandable one:

console.log(
  Array(8).fill(0).map((_, i) => Number(i))
);

Related