In JavaScript, you can also add array elements during program execution.

var cities = ["Sochi", "New York"];
alert("cities.length=" + cities.length);

var years = new Array(1969, 1970);
years[46] = 2015; //You can add array elements in this way.
alert("years.length=" + years.length);

alert("years=" + years);

for (var idx in years) {

Array's methods

  • splice(): Remove specific elements from an array and create a new array with that elements. when you create a new array, you can add other elements.
  • slice(): Returns a new array of parts of the array.
  • concat(): Combines two or more arrays and returns a copy of the combined array.
  • reverse(): Flips the order of the array.

concat() and slice() do not change the original array and return the result as a new array.
The JavaScript engine converts the array into a string separated by a comma (,).

var words = new Array('A','B','C','D','E');
var s1 = words.splice(2,2,'c','d');//Remove 2 from index 2 and add 2 elements 


var s2 = words.slice(2,4);//Returns a new array from index 2 to index 3 (not including index 4).

for .. in

var lang = ["C", "JAVA", "javascript"];
for (var idx in lang) {

Associative arrays

Associative arrays can not access an element using an index.
When you create an associative array, you typically use Object.
The array is automatically expanded whenever a new element is added.

var account = new Object();

account["accountNo"] = "1111-2222-3333";
account["name"] = "John Doe";
account["balance"] = 30000;


The following shows how to access an element in an associative array.

//Access the getElementsByTagName() element of the associative array document.
//Access the element ceil() of the associative array Math.

The following for statement prints all elements of the document object.

for (var property in document) {
	alert(property + ":" + document[property]);

The above example has different results for different browsers.
A JavaScript object is an associative array.