JavaScript: Array Basics

By Xah Lee. Date: . Last updated: .

Creating Array

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

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

Example of assigning array items one at a time:

var aa = [];  // define a array
aa[0] = "zero"; // assign a value to a element
aa[1] = "one";
aa[3] = "more"; // non-existent element automatically extend the array

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

var arr = [];
for (var i = 1; i <= 9; i++) { arr.push(i); }

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

Array Length

myArray.length returns the number of elements in myArray.

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

Access Array Element

Access a element. myArray[index]

var aa = [2, 4, 1];

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

Modify Array Element

Modify a element.

var aa = [2, 4, 1];

aa[0]= "no";

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

Nested Array

Array can be nested.

var 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
var aa = [3,7,4];

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

Other common way of going thru a array is array methods: {map, forEach}. See: JavaScript: Array.prototype.map

Array How-To

JavaScript: Array How-To

Array Methods

JavaScript: Array.prototype

Understand JS Array

JavaScript: Understand JS Array

JavaScript Basics

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

Array Topic

  1. JavaScript: Array Basics
  2. JavaScript: Understand JS Array
  3. JavaScript: Create Array
  4. JavaScript: Sparse Array
  5. JavaScript: What's Array-Like Object?
  6. JavaScript: How to Convert Array-Like Object to Array?
  7. JavaScript: Array How-To

  1. JavaScript: Array Object
  2. JavaScript: Array.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.