Tutorials Tonight's Logo
Follow Us


In javascript, an array is a special variable that can hold a collection of data in a single variable. The array data may be of similar or different Data types.


[21, 25, 54, 2, 46, ...]

Unlike arrays in C, C++, Java which store only the same data type in an array, javascript can store any kind of data type in an array.

The array data stored in memory are in contiguous memory location.

The location of any element in an array is defined by its index value. Index in array starts at 0. Means, 1st element stays at index 0, 2nd element at index 1 and so on. Look in the image below.

javascript array showing indexes

Array declaration in Javascript

Array can be defined in javascript in basically two ways:

  1. Using Array literals
  2. Using constructor

1. Creating Array using array literal

Creating an array using array literal is simple. Almost all the time the array literal is used to create the array.

It is simple to use, array is defined as a normal variable and the values of array is given in a square bracket separated by commas.

var empty = [];
var numeric = [2, 5, 12, 50, 25];

var float = [12.5, 34.0, 5.1, 68.3, 60.4];

var string = ["Heloo", "World", "john", "smith"];

var mixed = [true, "hello", 45, 2.6, 25, false];
▶ Run the code

2.Creating Array using array constructor

Array is defined using array constructor as var arr = new Array();, this creates an array of length 0.

Using array constructor length of array can be assigned while defining array.

var zeroLength = new Array(); // array with 0 length

var empty = new Array(5); // array with length 5 but all undefined value

var numbers = new Array(23, 34, 54, 2, 50); // array length = 5

var fruits = new Array("mango", "pineapple", "orange", "coconuts");
▶ Run the code

Adding Array Element

Array elements can be directly added while defining an array and can also be added to new elements after defining.

New array element is defined by arrayName[indexValue] = "newValue".

var arr = [5, 10, 15];
arr[3] = 20; // [5,10,15,20]
arr[4] = 25; // [5,10,15,20,25]
▶ Run the code

Accessing Array Element

Elements of the array are accessed using index value.

Index of array starts at 0. To access element write arrayName[indexValue]. For example if you want to get the 1st element then write arrayName[0].

var vehicles = ["Car", "bike", "boat", "bicycle", "train"]
document.getElementById("1st").innerHTML = vehicles[0];
document.getElementById("2nd").innerHTML = vehicles[1];
▶ Run the code

Change array elements

To change array elements in javascript just write the name of the array with the index value you want to changed and assign a new value. Example array[0] = "new value". Here array value at index 0 is change to "new value".

var arr = ["john", "smith", 23, 55, "hello"];
arr[1] = "carnor"; // ["john", "carnor", 23, 55, "hello"]
▶ Run the code

Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.