JS: 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

myArray.length return the number of elements in myArray.

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

Access Array Element

Access a element. myArray[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 JS: 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.

Array How-To

JS: Array How-To

Array Methods

JS: Array.prototype

Understand JS Array

JS: Understand JS Array

JavaScript Basics

  1. JavaScript Basics
  2. Value Types
  3. true, false
  4. Operators
  5. Variable
  6. if then else
  7. for while do Loop
  8. Array Basics
  9. Object Basics
  10. RegExp Tutorial

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To
  7. JS: Array Object
  8. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc