Array Basic Expalanation

Array is a special type of variable that can hold/contain more than one value at a time.

Look at the example bellow

var city1="Dhaka";
var city2="New York";
var city3="Sydney";
var city4="London";

In the above example, there are four variables and every variable contain one value or one city name.

But….an array?

An array can hold all those values into it. Look at the example…

var cities = ["Dhaka", "New York", "Sydney","London"];
document.getElementById("city1").innerHTML = cities;

Thus, Syntax of creating array is:

var array_variable_name = [item1, item2, item3, item4…];

Note:

    • You can not use comma at the end of last item, Look at example-this bellow code can fail on some browser like IE-8
var cities = ["Dhaka", "New York", "Sydney","London",];
    • You can use space and white space easily, Look at bellow code:
var cities = [
"Dhaka",
"New York",
"Sydney",
"London"
];

We can create array different ways, We have already

learn Best way like bellow:

var cities = ["Dhaka", "New York", "Sydney","London"];

Another way is mentioned bellow:

var cities = new Array("Dhaka", "New York",
 "Sydney","London");
document.getElementById("city2").innerHTML = cities;
    • Array Index start from 0(zero), so
cities[0]="Dhaka";
cities[1]="New York";
cities[2]="Sydney";
cities[3]="London";
    • If we print cities[2], we shall get Sydney as value
    • We can get array size or length by using following code:
    • length:

var lengthOfCities=cities.length;
document.getElementById("city3").innerHTML = lengthOfCities;

Array length proerties returns the size of Array:

var lengthOfCities=cities.length;

Array sort() method sorts the Array at assending order by default, Look at simple example:

Example of sort() method

var sortedCities=cities.sort();

Array sort() method sorts the Array at assending order by default, Look at simple example:

Example of sort() method

 

 var sortedCities=cities.sort();

Download Complete Source

Leave a Reply