Javascript Array

Updated on 01 Mar 2012,
Published on 12 Mar 2008

In JavaScript you can also use Arrays likewise in other programming languages, to store the set of values of same datatype in a single variable. To define an Array in JavaScript new Keyword is used.

In JavaScript you can define arrays in two ways. First by leaving the array size blank that allows it to define its size automatically. If you leave the array size undefined, then you add as many values at different index of array. In second way you can define the size of array by passing the integer value for proper memory allocation.

JavaScript Basics Examples:

You can see the live samples and examples of JavaScript Basics from the following links:

Syntax1
var myArr = new Array();
Syntax2
var myArr = new Array(5);

Also note that if you have defined the array size then you can add values for the array indexes 0 to 4. 

Example for array having no size defined
var myArr =  new Array();

myArr[0]  = "John";

myArr[1] = "Tim";

myArr[2] = "Smith";

myArr[3] = "Jack";
Example for array having size limit defined
var myArr =  new Array(3);

myArr[0]  = "John";

myArr[1] = "Tim";

myArr[2] = "Smith";

One another way of defining an Array in JavaScript:

var myArr = new Array( "John", "Smith", "Tim");

Now you have learnt how to define the arrays in JavaScript, then why to waste time for searching here and there to learn how to display the values stored at the different indexes of array.

You can directly call the array values by passing the specific index of the array: alert(myArr[0]);

Above code will display the value stored at the first i.e. 0th index of array.

If you have passed the two different values for the same index of an Array then calling that particular index will return the last value stored in it. 

Example
var myArr = new Array();

myArr[0] = "John";

myArr[1] = "Smith";

myArr[0] = "Tim";

alert(myArr[0]);

Above code will display the value "Tim" for 0th index.

You can also use the JavaScript for loop to read the each value in sequence from 0th to the last index of array.

Output:

You can see the output of above discussed codes from the following link:

JavaScript Array Object

Learn from JavaScript split function to convert the string into array and read the array values by using for loop in javascript.

0 Responses to "Javascript Array"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers