JS: Array Constructor

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

Same as

Array(args)

Array()

Return a empty array.

console.log(Array());
// []
Array(not_int)
  • not_int is not a integer.
  • return a array with a single element not_int.
console.log(Array("a"));
// [ "a" ]
Array(int_n)
  • int_n is integer.
  • Return a Sparse Array with length int_n.
  • If int_n is negative, RangeError.
console.log(Array(4));
// [ <4 empty items> ]

🛑 WARNING: Array(n) creates sparse array. Using method map on it doesn't work, because there is no item to map to.

// creating array by Array(n) and map doesn't work
console.log(Array(3).map(() => 1));
// [ <3 empty items> ]
Array(v1, v2, etc)

array of items v1, v2, etc.

🟢 TIP: better is Array.of

console.log(Array(3, 4));
// [ 3, 4 ]

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

Example. Array of int

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

Example. Array range

use with Array.prototype.keys, and Array.from .

console.log(Array.from(Array(4).keys()));
// [ 0, 1, 2, 3 ]

// you need Array.from to actually turn it into array
console.log(Array.isArray(Array(4).keys())); // false
console.log(Array.isArray(Array.from(Array(4).keys()))); // true

JavaScript. Array