JS: Create Array

By Xah Lee. Date: . Last updated: .

Array literal expression

// array literal expresion
const x = [3, 4];
console.log(x);
// [ 3, 4 ]

Array.of literal elements

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

Convert iterable to array

Array of the same item

// create array with 4 elements, all 0
console.log(Array(4).fill(0));
// [ 0, 0, 0, 0 ]

Array with integer sequence. range function

// create array with a range of integer
console.log(
 Array.from(Array(4).keys()),
);
// [ 0, 1, 2, 3 ]

Array constructor