JS: Create Array

By Xah Lee. Date: . Last updated: .

Literal Expression

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

One Single Trailing Comma is Ignored

// one trailing comma is ignored
const xx = [3, 4,];
console.log(xx);
// [ 3, 4 ]
console.log(xx.length === 2);
// true

Repeated Comma Creates Sparse Array

Repeated comma creates a Sparse Array. (that is, element of that index does not exist)

// repeated comma creates a sparse array.
const x = [9, ,4];

console.log( x );
// [ 9, <1 empty item>, 4 ]

console.log( x.length);
// 3

console.log(
Object.getOwnPropertyNames(x)
); // [ '0', '2', 'length' ]
// note, no property key "1"

Array Constructor

JavaScript. Array