Defining Array

ECMAScript 5
var arr1 = [1, 2, 3];

var arr2 = new Array(1, 2, 3);

Array is a container for a sequence of items.

There are 2 main ways to create Arrays in JavaScript:

  • Literal syntax
  • Array class

The elements inside the Array don't need to have the same type.

In JavaScript, Arrays are of type Object.

typeof [] === "object"

Array Length

ECMAScript 5
var arr = [1, 2, 3];

var length = arr.length;  // 3

The length property returns the length of an Array.


Get Element at index

ECMAScript 5
var animals = ["Cat", "Dog", "Cow"];

var cat = animals[0];   // Cat

Array elements can be accessed by their index.

In JavaScript, the Array Index starts from 0.


Set Element at index

ECMAScript 5
var animals = ["Cat", "Dog", "Cow"];

animals[0] = "Lion";

Here we are setting an element at index 0 to a value Lion.

So now animals array values are Lion, Dog, Cow.


Append Element

ECMAScript 5
var arr = [1, 2, 3];

arr.push(4);  // arr -> [1,2,3,4]

You can append an element to the end of an Array using push() method.


Find Element

ECMAScript 5
var animals = ["Cat", "Dog", "Cow"];

var index = animals.indexOf("Dog");  // 1

The indexOf() method searches for the index of the first occurrence of an element inside an Array.

If the element does not exist, it returns -1.


Get SubArray

ECMAScript 5
var animals = ["Cat", "Dog", "Cow"];

var sub1 = animals.slice(2);     // ["Cow"]
var sub2 = animals.slice(2, 3);  // ["Cow"]

The slice() method gets starting index (inclusive) and ending index (exclusive) and returns the SubArray for those parameters.

If you don't specify the second parameter, slice() will return the SubArray from starting point to the end of the Array.


Sort Array

ECMAScript 5
var arr = [2, 4, 3, 1];

arr.sort();  // arr -> [1,2,3,4]

Array sort() method sorts an Array in Ascending order.

If you want to sort an Array in descending order, you can use reverse() method after sort() or you can pass a comparing function to sort(), to let it know what logic should it use for ordering the Array elements.


Convert to String

ECMAScript 5
var animals = ["Cat", "Dog", "Cow"];

var str = animals.join(',')  // "Cat,Dog,Cow"

The join() method concatenate Array elements and returns a String.

It gets a string, and use that as a delimiter between elements in the string.