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 ]

Create Array with n Elements by constructor

// create array with 4 elements, all 0
console.log(Array(4).fill(0));
// [ 0, 0, 0, 0 ]
// create array with a range of integer
console.log(Array.from(Array(4).keys()));
// [ 0, 1, 2, 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: Property Dot Notation vs Bracket Notation

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

Modify Array Element

🛑 WARNING: you should not modify array element like this. because it is easy to go out of bound and create Sparse Array.

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

Change Array Element, return new copy

Nested Array

Array can be nested.

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

Loop Over Array

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.

JavaScript. Array