JavaScript: Array Basics

By Xah Lee. Date: . Last updated: .

Array is a data structure that holds a sequence of values, in order.

Each value is “indexed” by a integer, starting from 0.

Creating Array

The basic syntax to create a array is: [expr_0, expr_1, expr_2, …].

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

Example of assigning array items one at a time:

const aa = [];  // define a empty array
aa[0] = "zero"; // assign a value to a element
aa[1] = "one";
aa[3] = "more";

console.log(aa); // [ 'zero', 'one', , 'more' ]

// value of aa[2] is “undefined”

Creating a Array with n Elements

// creating array with n elements, 1 2 3 ... n

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

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

Array Length

arrayX.length return the number of elements in arrayX.

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

Access Array Element

Access a element. arrayX[index]

const aa = [2, 4, 1];

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

Modify Array Element

Modify a element.

const aa = [2, 4, 1];

aa[0]= "no";

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

Nested Array

Array can be nested.

const aa = ["pa", ["deep", [4,5]], 3];
console.log(aa[1][1][0]); // prints 4

Loop thru Array

Best way to loop thru array is by using “for of” loop.

[see for-of Loop]

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

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

Here's “for of” loop with index and value:

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

for (let [i,x] of aa.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 aa = [3,7,4];

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

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

JavaScript Array

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc