Xah Talk Show 2025-05-16 Ep656 Why JavaScript Sucks, Part 2, Array

// javascript array is not true array

// normal array syntax
const xx = ["a", "b", "c"];

console.log(Array.isArray(xx) === true);

// however, you can access the element just as if it's an object
// using keys of string type.
// and there is a magical property string key length
console.log(xx["0"] === "a");
console.log(xx["1"] === "b");
console.log(xx["2"] === "c");
console.log(xx["length"] === 3);

// array-like object
const xObj = { "0": "a", "1": "b", "2": "c", "length": 3 };
console.log(xObj);
// { "0": "a", "1": "b", "2": "c", length: 3 }
console.log(Array.isArray(xObj) === false);
console.log(Array.isArray(Array.from(xObj)));

console.log(xx[0]);
console.log(xObj[0]);

// sparse
// one example of creating spare array
const sparseArray = Array(4);
console.log( sparseArray )
// [ <4 empty items> ]
console.log( sparseArray.map( ((x) => 1) ) )
console.log( Array(4).fill( 0 ) )
console.log( Array(4).fill( undefined ) )

// [ undefined, undefined, undefined, undefined ]
// [ null, null, null, null ]


// HHHH------------------------------

// sparse
// one example of creating spare array
const xar = ["a", "b", "c"];
delete xar["0"]

console.log( xar )
// [ <1 empty item>, "b", "c" ]

console.log( Reflect.ownKeys( xar  ) )
// [ "1", "2", "length" ]

console.log( xar.length )
// 3

console.log( xar.map( (( x, i) => [x,i]) ) )
// [ <1 empty item>, [ "b", 1 ], [ "c", 2 ] ]

console.log( xar.length === 3)
// HHHH------------------------------


const yy = Array(3);
console.log(yy);
// [ <3 empty items> ]
console.log( Array.isArray( yy ) )
// true

const zz = Array(3).fill(0);
console.log(zz);
// [ 0, 0, 0 ]

Array.isArray(yy === true);
const xObj = { "0": "a", "1": "b", "2": "c", "length": 3 };
console.log(xObj);
// { "0": "a", "1": "b", "2": "c", length: 3 }

const xx = ["a", "b", "c"];
console.log(xx);
// [ 1, 2, 3 ]

console.log(Reflect.ownKeys(xx));
// [ "0", "1", "2", "length" ]

why JavaScript sucks