A Platform To Learn To Code

JAVASCRIPT ARRAY



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.

Example:

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

Example

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.

Example

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

Example

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

Example

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

Example

Run the code