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.
- Using Array literals
- 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.
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.
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".
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
Change array elements
array = "new value". Here array value at index 0 is change to "new value".