JS: Create Array
There are 2 ways to create a array:
- by literal expression, e.g.
[3,4,5]
- by constructor, e.g.
Array(9)
. γsee Array Constructorγ
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"