JavaScript Array Object

« Previous Chapter Next Chapter »

The Array object is used to store multiple values in a single variable.

Code it Online - Examples

For...In Statement
How to use a for...in statement to loop through the elements of an array.

What is an Array?

An array is a special variable, which can hold more than one value, at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

var car1="Sachin";
var car2="Pointing";
var car3="Maxwell";

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The best solution here is to use an array

An array can hold all your variable values under a single name. And you can access the values by referring to the array name.

Each element in the array has its own ID so that it can be easily accessed.

Create an Array

An array can be defined in three ways.

The Below code creates an Array object called CricPlayers:

1:

var CricPlayers=new Array(); // regular array (add an optional integer
CricPlayers[0]="Sachin";       // argument to control array's size)
CricPlayers[1]="Pointing";
CricPlayers[2]="Maxwell";

2:

var CricPlayers=new Array("Sachin","Pointing","Maxwell"); // condensed array

3:

var CricPlayers=["Sachin","Pointing","Maxwell"]; // literal array

Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean, instead of String.

Access an Array

You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.

The Below code line:

document.write(CricPlayers[0]);

will result in the following output:

Sachin


Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified index number:

CricPlayers[0]="Maxwell";

Now, the following code line:

document.write(CricPlayers[0]);

will result in the following output:

Maxwell


« Previous Chapter Next Chapter »

Have Any Suggestion? We Are Waiting To Hear from YOU!

Your Query was successfully sent!