Rami Chasygov
Rami Chasygov

Reputation: 2784

Difference between new Array(7) and Array.apply(null, Array(7))

Anyone can explain me difference between new Array(7) and Array.apply(null, Array(7))? In context:

Array.apply(null, Array(7)).map((e, i) => {
  return moment(i, 'e').format('ddd');
}); // ["Sun" ,"Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]

new Array(7).map((e, i) => {
  return moment(i, 'e').format('dd');
}); // [empty × 7]
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment-with-locales.min.js"></script>

Upvotes: 2

Views: 265

Answers (3)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

Array.apply calls the prototype method on the Array object. Where as doing Array(7) is creating a new array of seven elements, as such new Array(7).apply is not a valid call and would give the following error:

Uncaught TypeError: (intermediate value).apply is not a function

Doing Array.apply(null, Array(7)) is the only valid call here.

Edit

The statement Array.apply(null, Array(7)) will create an array populated with undefined elements. As such calling .map() will iterate those elements and produce your expected result.

On the other hand calling just new Array(7) will create a sparse array with a define length of 7. Meaning the length will be defined as 7 but it didn't populate any elements into the array. So there is nothing to iterate over yet.

Upvotes: 3

Jonas Wilms
Jonas Wilms

Reputation: 138267

 Array(7)

creates a Sparse array with no elements set. So as an object it would look like:

 {length: 7}

If you would call any of the new cool array methods, it wouldnt iterate as there are no elements in the array. However if that is spread into the Array constructor:

  Array(...Array(3))

Its equal to

 Array(undefined, undefined, undefined)

And that actually creates 3 (or 7) undefined array slots:

 {
 0:undefined,
 1:undefined,
 2:undefined,
 length:3
 }

And now you can iterate over it with map etc. The same is possible with:

 Array(7).fill().map(func)

and

 Array.from({length:7}, func);

Upvotes: 3

Hitmands
Hitmands

Reputation: 14179

these two approach are equivalent since Function.prototype.apply is part of the Function api.

it looks you likely need something like:

Array
  .from({ length: 7 }, (_, i) => moment(i, 'e').format('ddd'))
;

Upvotes: 1

Related Questions