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(number)
  • number is integer.
  • Return a Sparse Array with length number.
  • If number is negative, RangeError.
  • If number is floating number, RangeError.
console.log(Array(4));
// [ <4 empty items> ]
try {
 console.log(Array(1.23));
} catch (xerror) {
 console.log(xerror);
}
// RangeError: Invalid array length

🛑 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(not_number)
  • not_number is not a integer.
  • return a array with a single element not_number.
console.log(Array("a"));
// [ "a" ]
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

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