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");
Since JS Array is a Object, we can add property to array that's not an integer.
const xx = [3, 4]; // array is a object, you can add properties to it xx.yy = 7; console.assert(Object.hasOwn( xx, "yy" )); console.assert(xx.yy === 7);
Array also has the attribute “extensible”, just like other objects. [see Prevent Adding Property]
console.assert(Object.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"));
Reading Non-Existent Index Return Undefined
// accessing array with non-existent index results undefined const xx = [3]; console.assert(xx[200] === undefined);
Check if a object is true array
Length special property
Every array object has a special property key "length".
It is the object's own property, and is a key of type string.
The “length” property is automatically updated when array elements are added or removed using
Array.prototype
methods.
Array length can be set. If you set it, the array will be lengthened or shortened.
- When lengthened, it creates a Sparse Array.
- When shortened, extra elements are removed.
// creating a sparse array by setting the length property const xx = ["a", "b"]; // set the length property beyond the last index xx.length = 5; console.log(Object.getOwnPropertyNames(xx)); // [ "0", "1", "length" ] console.log(xx); // [ "a", "b", <3 empty items> ]
// truncating a array by setting the length const xx = [1, 2, 3, 4, 5]; console.log(Object.getOwnPropertyNames(xx)); // [ "0", "1", "2", "3", "4", "length" ] xx.length = 1; // index 1 doesnt exist console.log(xx[1]); console.log(Object.getOwnPropertyNames(xx)); // [ "0", "length" ]
[see Array.prototype.length]
Array methods
String to Array
Array is iterable
That means, you can use for-of Loop and Spread Operator on them.