JS: Array Constructor

By Xah Lee. Date: . Last updated: .

Array Constructor

new Array(args)

Same as

Array(args)

Array()

Return a empty array.

console.log(Array());
// []

console.log(Reflect.ownKeys(Array()));
["length"];
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> ]

console.log(Reflect.ownKeys(Array(4)));
// [ "length" ]

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

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

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

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

🛑 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" ]

JavaScript. Array