JavaScript: Array Constructor

By Xah Lee. Date: . Last updated: .
new Array(args)

Same as

Array(args)

Array()

Return a empty array.

Array(not_int)
  • not_int is not a integer.
  • return a array with a single element not_int.
const xx = Array("a");
console.log(xx);
// [ "a" ]
Array(int_n)
  • int_n is integer.
  • Return a Sparse Array with length int_n.
  • If int_n is negative, RangeError.

Use together with Array.prototype.fill to fill array.

console.log(Array(4).fill(0));
// [ 0, 0, 0, 0 ]
Array(v1, v2, etc)

array of items v1, v2, etc.

const xx = Array("a", "b");
console.log(xx);
// [ "a", "b" ]

🛑 WARNING: Array(n) Creates Sparse Array

Array(3) does not create any element. Using method map on it doesn't work, because there is no item to map to.

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

// compare to,
const yy = [undefined, undefined];
console.log(Object.getOwnPropertyNames(yy)); // [ "0", "1", "length" ]
// creating array by Array(n) and map doesn't work

const xx = new Array(3);
const yy = xx.map(() => 9);
console.log(yy);

// [ <3 empty items> ]
// expected [9, 9, 9]

console.log(yy[0] !== 9);

JavaScript Array

BUY ΣJS JavaScript in Depth