JS: Array Basics

By Xah Lee. Date: . Last updated: .

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

The most useful way to go thru every element of 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: {map, forEach}. See: JS: Array.prototype.map

Array How-To

JS: Array How-To

Array Methods

JS: Array.prototype

Understand JS Array

JS: Understand JS Array

JavaScript Basics

  1. How to Run JavaScript
  2. JS: How to Use Browser Console
  3. JavaScript Basics
  4. JS: Data Types
  5. JS: true, false
  6. JS: Operators
  7. JS: Variable
  8. JS: Branch Control: if then else, switch
  9. JS: for while do Loop
  10. JS: Array Basics
  11. JS: Object Basics
  12. JS: RegExp Tutorial
  13. JS: Throw Try Catch Finally

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

  1. JS: Array Object
  2. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon