JavaScript Arrays Standard array initialization


There are many ways to create arrays. The most common are to use array literals, or the Array constructor:

var arr = [1, 2, 3, 4];
var arr2 = new Array(1, 2, 3, 4);

If the Array constructor is used with no arguments, an empty array is created.

var arr3 = new Array();

results in:


Note that if it's used with exactly one argument and that argument is a number, an array of that length with all undefined values will be created instead:

var arr4 = new Array(4);

results in:

[undefined, undefined, undefined, undefined]

That does not apply if the single argument is non-numeric:

var arr5 = new Array("foo");

results in:


Similar to an array literal, Array.of can be used to create a new Array instance given a number of arguments:

Array.of(21, "Hello", "World");

results in:

[21, "Hello", "World"]

In contrast to the Array constructor, creating an array with a single number such as Array.of(23) will create a new array [23], rather than an Array with length 23.

The other way to create and initialize an array would be Array.from

var newArray = Array.from({ length: 5 }, (_, index) => Math.pow(index, 4));

will result:

[0, 1, 16, 81, 256]