JS: Array (basics)

By Xah Lee. Date: . Last updated: .

Create array (array literal expression)

[value1, value2, etc]

console.log([1, 2, 3]);
// [ 1, 2, 3 ]

// elements with mixed types
console.log(["one", 3]);
// [ "one", 3 ]

Length

xArray.length return the count of elements.

console.log([7, 8, 2].length);
// 3

Get an element

via at (method)

// get a element
console.log([3, 4].at(0));
// 3

console.log([3, 4].at(-1));
// 4

via bracket operator

xArray[index]

index cannot be negative.

This is the bracket notation for property access. [see JS: Dot vs bracket syntax for property access]

// get a element
console.log([17, 4, 1][0]);
// 17

Modify array element

const xx = [2, 4, 1];
xx[0] = 99;
console.log(xx);
// [ 99, 4, 1 ]

Out of bound

if index is out of bound, result is a Sparse Array.

const xx = [0, 1];
xx[4] = 99;
console.log(xx);
// [ 0, 1, <2 empty items>, 99 ]

Nested array

Array can be nested.

const xx = [3, [4, 5]];
console.log(xx[1][1]);
// 5

Loop over array

for (let x of [3, 4, 5]) {
  console.log(x);
}
/*
3
4
5
*/

Clear all array elements

const xx = [3, 4, 5];
xx.splice(0);
console.log(xx.length);
// 0

Note, it's different from simply assign it a new empty array such as

xArray = []

Because that gives the variable xArray a new value.