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?

2
  • Can't reproduce -> jsfiddle.net/70swc53z Commented Oct 1, 2016 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 Commented Oct 1, 2016 at 20:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.