Array in JavaScript
- Array Definition
-
In JavaScript arrays are different from arrays of other languages.
-
Traditionally an array is considered to be a collection of homogeneous elements, which means that it cannot contain dissimilar elements.
-
But JavaScript does not follow this concept.
-
A JAVASCRIPT ARRAY CAN CONTAIN HETROGENEOUS ELEMENTS
-
Thus we can say that arrays in JavaScript are similar to structure of C language except that they are accessed using an index.
Creating An Array
-
Using Array Literal.
-
1.Using Array Constructor.
Array Literals
Array literals are written using [ ] containing array elements separated with commas.
var <array name>=[value,value,. . . ];
Example:
var nums=[2,5,8,3,9];
var colors=[“red”,”green”,”blue”];
Another way of using Array Literals is that we can leave the [ ] empty and fill values afterwards.
var num=[ ]; /* declares the array */
num[0]=2; /* initializes it */
num[1]=5;
num[2]=8;
num[3]=3;
num[4]=9;
Array With “undefined” Values
var colors=[“red”, , ,”green”,”blue”];
The above array has 5 elements, from colors[0] to colors[4]. But since colors[1] and colors[2] have not been initialized they are automatically set to "undefined"
Using “length” Property
JavaScript arrays are Objects and hence they have some predefined properties and methods which help makes it easier for a programmer to handle them.
The “length” property returns the size of the array.
var nums=[2,5,3,8,6,9];
alert(nums.length); // will show 6