JavaScript: Array Constructor

By Xah Lee. Date: . Last updated: .
new Array()
same as Array().
Return a empty array. Same as [].
n is integer. Return a Sparse Array with length n. If n is negative, RangeError.
x is not a integer. Result is a array with a single element x.
Array(a1, a2 )
same as [a1, a2].

warning: Array(9) does not actually create any element in the array at all.

// 「new Array(2)」 does not create any elements, only sets length
const r1 = new Array(2);
console.log(r1.length); // 2
console.log(Object.getOwnPropertyNames(r1)); // [ 'length' ]

// compare to,
// here's array of 2 items, both are undefined
const r2 = [undefined, undefined];
console.log(r2.length); // 2
console.log(Object.getOwnPropertyNames(r2)); // [ '0', '1', 'length' ]

If you create a array by Array(4), then use the array method map to fill in, it doesn't work.

// creating array by map this way doesn't work

const a1 = new Array(3);

const a2 = (() => "v"));

console.log(a2); // [ <3 empty items> ]

// expected ['v','v','v',]

console.log( a2[0] === undefined); // true

Use Fill

Use Array.prototype.fill to fill sparse array. Example:


Range Function for Creating Array

Range Function for Array

JavaScript Array

JavaScript in Depth

JS Obj Reference