JS: Create Array

By Xah Lee. Date: . Last updated: .

There are 2 ways to create a array:

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 OK

One single comma at the end is ignored.

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

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"

Range Function for Creating Array

Range Function for Array πŸš€

JavaScript, Array