JS: Array (overview)
Array syntax
Array is object type with special purpose
JavaScript array is a
Object,
with a magic property key "length",
and special treatement of
non-negative integer
string property keys "0", "1",
"2", etc.
console.assert(typeof [3, 4] === "object");
because array is a Object type, we can add any property to it.
const xx = [3, 4]; xx.dog = 7; console.log(xx); // [ 3, 4, dog: 7 ]
const xx = [3, 4]; // array is a object, you can add properties to it xx.dog = 7; console.assert(Object.hasOwn(xx, "dog")); console.assert(xx.dog === 7);
Array also has the attribute “extensible”, just like other objects. [see Prevent Adding Property]
console.assert(Reflect.isExtensible([3, 4]));
Index vs property key
The index of array is the same as string property key.
console.assert(Object.hasOwn([3, 4], "0"));
Value of non-existent index
// accessing array with non-existent index results undefined const xx = [3]; console.assert(xx[200] === undefined);
Check if a object is true array
Magic property: length
Array methods
String to Array
Array is iterable
That means, you can use for-of Loop and Spread Operator on them.