Create an array in JavaScript

JavaScript arrays are used to store multiple values in a single variable. An array can hold many values under a single name, and you can access the values by referring to an index number.

Syntax:

var array-name = [item1, item2, …];      

Example:

//Let's create an array using array literal notation
var bike = ['road', 'mountain', 'cruizer'];

//update the third item in the array
bike[2] = 'hybrid';

//print the third item in the array
document.write(bike[2]);

//Let's create an array using array constructor
var moreBikes = new Array(
 'road',
 'mountain',
 'cruizer');

//update the third item in the array
moreBikes[2] = 'hybrid';

//print the third item in the array
document.write(moreBikes[2]);

In this example an arry is declared in two distinct ways.

  1. we can define an arry using type inference from a literal.
  2. we can define an arry using keyword “new Array”.

Empty Array

To create an empty array it is best to use empty array symbol = [].

var fruits = []

Push()

To add elements into an array we can use array method push().

fruits.push(“Banana”);

fruits.push(“Orange”);

fruits.push(“Apple”);

Pop()

To remove last element from array we can use method pop();

fruits.pop(); => Apple

Shift()

To remove first element from array we can use method shift();

fruits.shift(); => Banana

Unshift()

To add element as first element in array we can use method unshift();

fruits.unshift(“Mango”);

Slice()

The slice(first, last) method slices out a piece of an array into a new array but the old array remain unchanged. To change the old array we use splice() method.

var fruits = [“Banana”, “Orange”, “Lemon”, “Apple”];
var citrus = fruits.slice(1, 3);

=> citrus  = [“Orange”, “Lemon”]

 

Splice()

The method splice(start_position, how_many) is removing elements from array.

var fruits = [“Banana”, “Orange”, “Lemon”, “Apple”];
var citrus = fruits.splice(1, 2);

=> fruits =  [“Banana”, “Apple”];

Splice() method can be used to insert elements into array using a third parameter.

splice(start_position, how_many, new_elements)

var fruits = [“Banana”, “Orange”, “Lemon”, “Apple”];
fruits.splice(2, 0, “Mango”);

=> fruits =  [“Banana”, “Orange”, “Mango”, “Lemon”, “Apple”]

 

See also:  complete refference