Konrad Viltersten
Konrad Viltersten

Reputation: 39078

What's the first argument of Array.apply in JavaScript?

In an answer, @Tushar suggested the syntax corresponding to the following.

Array.apply(null, Array(3).fill(10))
  .map(function (item, index) { 
    return item + index;
  });

I do understand what's going on here and I'm satisfied. However, it bugs me a bit that there's this null valued argument doing seemingly nothing. So I went off and started researching. According to the wisdom on the web, it's a reference to this. Now, that gave me very little clarity and despite of putting in cucumbers, arrays, and objects into that, it didn't affect jack, as far I could tell. In fact, I'm curious why the following wouldn't be equivalent, let alone suffice.

Array(3).fill(10)
  .map(function (item, index) { 
    return item + index;
  });

Further on, I read something about Cr an IE not accepting array-like objects, which tells me even less. Also, it's a bit hard to verify the age of the article so the validity of its claim's hard to assess. I got as far as to the talk about prototype constructors and gave up, not being sure if I'm on the right path.

Upvotes: 2

Views: 1887

Answers (2)

Conrad.Dean
Conrad.Dean

Reputation: 4421

The first argument of apply is only important if you're using a function that uses this.

Running the following snippet should make it a little clearer:

var o = {value: 1};

var fn = function(a) {
    console.log(a + this.value);
}
value = "something else";

fn("an argument ");
fn.apply(o, [20]);

// the above prints:
// an argument something else
// 21

https://jsfiddle.net/f2zw8edd/

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

Array(number) creates an array of the given size, however it does not populate any of its data points. Calling map or fill or pretty much anything else on it therefore won't do anything useful.

Array(item1, item2, item...) on the other hand creates an array with the given items as elements of the array. You can call map, fill, whatever you want on this and it will work.

So how can you use this to create an array of a given size that you can call map on? Exactly the way you see.

What Array.apply(null,Array(3)) does is create an unpopulated array of size 3, then passes those 3 undefined items as arguments to Array, thus resulting in
Array(undefined,undefined,undefined), which gives you a mappable array. It's important to note that you're creating two arrays here, but the Array(3) is discarded after use.

So why null? That would be because when creating an array, there is no place where this is relevant. Since the context is irrelevant, you can pass literally anything you want as the context and it will run just fine, but it's easiest to understand that context doesn't matter if you pass it null.

Upvotes: 0

Related Questions