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:
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.
Array declaration in Javascript
Array can be defined in javascript in basically two ways:
- 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 arrayName[0]
.
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".