name1="Amir"
name2="Khan"
name3="John"
....
....
...
name100="Ahmed"
so it becomes very cumbersome to hold and write the 150 variables in a program. In such scenario arrays comes handy.
Arrays are the special type of variable which can hold a list of values under single variable
name. For example above list of 150 student names can be easily defined using arrays. like
student = ["Amir","Khan","John"........................."Ahmed"];
Defining an Array in JavaScript
An array can be considered as collection of variables of same data type.
In JavaScript array can be declared as below.
var array_name = [item1, item2, ...];
or
var array_name = new array_name(item1,item2,item3.......);
For example
var student = ["Amir","Khan","John"..................."Ahmed"];
or
var student = new student("Amir","Khan","John"......"Ahmed");
How to access an array in JavaScript
An item in an array is called an element. An element in an array can be accessed using a numeric value called index.
For example in order to access the first element in above array we will write it as below
student[0];
Be remember that the first index of the array starts with 0 hence the last index of the array must be less than one of the total length of the array. For example
if an array contains 5 elements than the index for the last element is 4.
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
JavaScript Methods
toString() method converts the an array into strings separted by commas.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
pop() and push() methods are used to remove and add the new elements at the end of an array. For example.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits
and
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
Similarly shift() and unshit() methods are used to remove and add and element at beginning of the array.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.shift(); // the value of x is "Banana"
and similarly
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
It is also possible to loop through an array elements using for loop and Array.forEach() . For Example.
Below is the code snipt for looping through Array using array.forEach function.
var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];
text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";
function myFunction(value) {
text += "<li>" + value + "</li>";
}