var thearrayname=new Array(arraylength)
In the above syntax thearrayname is a variable like array. We can create an array only using the syntax “new Array()”. It’s case sensitive and so “Array” should not be defined as “array”. You can declare the size of the array in arraylength. So, we can store number of variables in the array that we have declared as arraylength. You can declare any size based on your requirement.
Declaring & Assigning Values:
var favColor=new Array(4); favColor="White"; favColor="Red"; favColor="Green"; favColor="Yellow";
Note: Look at the assignment here, you found that i have started from 0. Because Arrays always start from 0th index or position. If we have set the size as 4, the array will have 4 position of 0,1,2 & 3.
You can also declare in the following way:
var favColor=new Array("White","Red","Green","Yellow");
Note: Such arrays are known as “Dense Arrays“. They are declared by listing the values of the array elements in the declaration, in place of the array length.
Few more Information:
1. You can define any element values in any order.
2. You can increase the array length any time.
3. IF you want to assign a value in out range of array index, the value will be discarded.
We have learned how we can stroe values in an array. Now we will learn how we can read values from array. There were two ways we can read values. One is directly calling by index number & another one is looping through array.
Now if you want to print your 4th favorite color name then the code should be:
document.write("My favourite color is : "+favColor);
Now if we want to loop through the array & print all values then the code should be: