Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this array initialization shorthand work?

console.log(
  Array.from({ length: 3 }, Function.call, Number)
);

According to my understanding, the above code passes (value, index) to the .call method of the Function prototype.

And the this value of .call is set to Number.

So it's exactly the same as:

Array.from({ length: 3 }, (value, index) => Number.call(value, index))

In VSCode my tooltip describes the function as:

mapfn: (v: any, k: number) => any

That's where I got (value, index) from, assuming k means key/index.

But Number only accepts a single numerical argument. So it will accept value, and ignore index.

But value is undefined, because the array is not yet initialized.

So how is the code producing an array where each value is equal to its index, instead of full of NaN?

like image 258
GirkovArpa Avatar asked Mar 13 '26 05:03

GirkovArpa


1 Answers

The first argument .call accepts is the this value of the function to be invoked. The rest of the arguments are plain arguments that the function gets invoked with. So, this:

Number.call(value, index)

is equivalent to:

Number(index)

where the this value inside Number is set to value.

The value is indeed undefined, but the Number constructor doesn't care about its calling context, its this, so it effectively gets ignored and creates a number from the index.

Here's another way of looking at it: below is a function named foo, which, when .called, does not care about the first parameter, and only takes into consideration the second:

function foo(arg) {
  return 'foo' + arg;
}

console.log(
  foo.call('IGNORED PARAMETER', 'bar')
);
like image 79
CertainPerformance Avatar answered Mar 15 '26 17:03

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!