2

I am confused by Array.apply behaviour when using it to create an array.

See the following code:

Array.apply(null, { length: 6 })
Array.apply(null,new Array(6))

Both output [undefined, undefined, undefined, undefined, undefined, undefined] which is as you would expect, an array of 6 elements. On the other hand if you use the following snippet:

Array.apply(null, [6])

In this one the output is [undefined × 6] which does not make any sense.

Does anyone have a explanation for this behaviour?

  • Can't reproduce -> https://jsfiddle.net/70swc53z/ – adeneo Oct 01 '16 at 20:07
  • 1
    Oh, wait, it outputs that if you type it directly into the console, as it would be the same as `Array(6)`, returning an array with a length of `6` with undefined indices, and in this case undefined it truly not defined, not the value `undefined` – adeneo Oct 01 '16 at 20:14

1 Answers1

3

Some things to have in mind:

Array(6);     // Creates an array containing six empty slots
Array(null);  // Creates an array containing one null
Array(6,6,6); // Creates an array containing three 6
[6];          // Creates an array containing one 6
[null];       // Creates an array containing one null
[6,6,6];      // Creates an array containing three 6

Basically, when Array is called with a single argument which is a number, that value is considered to be the length of the array instead of the first item of the array.

Both

Array.apply(null, { length: 6 });
Array.apply(null, new Array(6))

behave like

Array(undefined, undefined, undefined, undefined, undefined, undefined);

so they create an array containing 6 undefineds.

But

Array.apply(null, [6]);

is like

Array(6);

so it creates an array with 6 empty slots.

Oriol
  • 274,082
  • 63
  • 437
  • 513