JS: Array

By Xah Lee. Date: . Last updated: .

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.

typeof [3, 4] === "object"

Since JS Array is a Object, we can add property to array that's not an integer.

const aa = [3, 4];

// array is a object, you can add properties to it
aa.xx = 7;

console.log(aa.hasOwnProperty("xx"));

Array also has the attribute “extensible”, just like other objects. 〔see Prevent Adding Property

Object.isExtensible( [3,4] )

Index vs Property Key

The index of array is the same as string property key.

[3, 4].hasOwnProperty("0")

Non-Existent Index Return Undefined

// accessing array with non-existent index results undefined
const arr = [3];
console.log(arr[200] === undefined);

Check If a Object is 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.

// creating a sparse array by setting the length property

const aa = ["a", "b"];

// set the length property beyond the last index
aa.length = 3;

console.log(aa.length); // 3

console.log( Object.getOwnPropertyNames(aa)); // [ '0', '1', 'length' ]

console.log(aa); // [ 'a', 'b',  ]
// truncating a array by setting its length

const aa = ["a", "b", "c"];
console.log(aa.length); // 3

aa.length = 1;

console.log(aa.length); // 1
console.log(aa[1]);     // undefined

console.log( Object.getOwnPropertyNames(aa)); // [ '0', 'length' ]

〔see Array.prototype.length

Array Methods

Common array operations should be done using array methods, such as shift, unshift, push, pop. 〔see Array.prototype

To add/remove element(s) in middle, use Array.prototype.splice.

String to Array

Max Number of Elements

The max number of elements is 2^32 - 1 (which is 4 294 967 295).

When the index is a number between 0 to 2^32-2, inclusive, it is treated as array index, else it's just a property key.

// When array index is beyond 2^32 - 2, it is treated as a property key.

const hh = ["a"];
hh[1] = "b";
hh[2**32] = "c";

console.log( 2**32 === 4294967296 );

console.log(hh); // [ 'a', 'b', '4294967296': 'c' ]
// note, the c is printed differently

console.log(
 Object.getOwnPropertyNames(hh)
); // [ '0', '1', 'length', '4294967296' ]
// all are property keys

Note: if you create a array with just 1,000,000 items, the browser will become not responsive.

Array is Iterable

That means, you can use for-of Loop and Spread Operator on them.

JavaScript, Array