JS: Create Array
Literal Expression
// array literal expresion const x = [3, 4]; console.log(x); // [ 3, 4 ]
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
🛑 WARNING: 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. Create Array with n Elements
// create array with 4 elements, all 0 console.log(Array(4).fill(0)); // [ 0, 0, 0, 0 ]
// create array with a range of integer console.log(Array.from(Array(4).keys())); // [ 0, 1, 2, 3 ]