JS: Array Tutorial

By Xah Lee. Date: . Last updated: .

Create Array

The basic syntax to create a array is:

[val1, val2, etc]

const xx = ["one", "two", 3];
console.log(xx); // [ 'one', 'two', 3 ]

Example of assigning array items one at a time:

// define a empty array
const xx = [];

// assign a value to a slot
xx[0] = 82;
xx[1] = 34;
xx[3] = 96;

console.log(xx);
// [ 82, 34, <1 empty item>, 96 ]

// value of xx[2] do not exist

Create Array with n Elements

There are many ways to create a array with 1 to n elements. Most common way is by for Loop

// create array with elements 1 2 3 ... n

const xx = [];
for (let i = 1; i <= 5; i++) xx.push(i);

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

Array Length

arrayX.length return the count of elements.

[7, 8, 2].length === 3

Access Array Element

Access a element. arrayX[index]

const xx = [2, 4, 1];

// access a element
console.log(xx[0] === 2);

Modify Array Element

Modify a element.

const xx = [2, 4, 1];

xx[0] = "no";

console.log(xx); // [ 'no', 4, 1 ]

Nested Array

Array can be nested.

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

Loop Over Array

use for-of Loop

// for-of loop on array
let xx = [3, 4, 5];

for (let x of xx) {
  console.log(x);
} // prints 3 4 5

Here is for-of Loop with index and value:

// for-of loop on array
let xx = ["a", "b", "c"];

for (let [i, x] of xx.entries()) {
  console.log(i, x);
}

// prints
// 0 'a'
// 1 'b'
// 2 'c'

The most general purpose way to go thru array is using β€œfor” loop.

// loop thru array
const xx = [3, 7, 4];

for (let i = 0; i < xx.length; i++) {
  console.log(xx[i]);
}

Other common way of going thru a array is array methods forEach and map.

Clear All Array Elements

To clear all array elements, use JS: Array.prototype.splice

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

arrayX = []

Because that gives the variable arrayX a new value.

JavaScript, Array