Javascript Arrays

An array is a collection of key/value pairs. We can store more than one item in a single variable. i.e. array. So, array is used when there is requirement to add more items in a single variable.

These are the two ways to create array in Javascript.

1. Creating an array using Array Literal.

Javascript array treats like a global object that is used to create an array.

var arr = ['mumbai', 'delhi', 'pune', 'channai'];

In the above example, we have created an array name 'arr' and each array element is separated by comma. This is the easiest way to create an array.

2. By using the new keyword.

We can also create array by using array constructor new Array().

var arr = new Array();

Example

var arr = new Array(11, 12, 13, 14, 15);    

Access array element

An array element can be accessed by its index that starts with index 0. We can use the [ ] brackets for indexing.

var arr = ['mumbai', 'delhi', 'pune', 'channai'];
var ele1 = arr[1];

Array push

Javascript provides push() function to add element to the end of an array.

var arr = ['mumbai', 'delhi', 'pune', 'channai'];
var newarr = arr.push('goa');

Array pop

Javascript provides pop() function to remove element from the end of an array.

var arr = ['mumbai', 'delhi', 'pune', 'channai'];
var newarr = arr.pop();

Get length of an array

Javascript provides length property to get length of an array.

var arr = ['mumbai', 'delhi', 'pune', 'channai'];
arr.length;

Array iteration

We can iterate through an array using for loop.

var arr = ['mumbai', 'delhi', 'pune', 'channai'];
var len = arr.length;
var x;
for (i = 0; i < len; i++) {
    x += arr[i] + "<br/>";
}





Read more articles


General Knowledge



Learn Popular Language