Javascript Array Tutorial - Initializing Array



Before you start using an array, you need to declare it. If you know the elements of the array before head, you can declare it as

var cars = ['Toyota', 'Honda', 'Audi'];

If you do not know the elements of the array beforehead, you can declare it as

var cars [] ;

You can then dynamically add the contents as required.

It is perfectly ok to create an array with a mixture of integers, strings and booleans. Javascript is a "loosely typed" language

var x = [1, 'referencedesigner.com', true, 43.34];
			

For ease of readability it is possible to list array element in separate lines

var quiz = [ 'How far is moon from sun',
'Who was the first President of USA ',
'What is the Capital of Texas',
'Who was gold medallist in 100 Meter race in 2012 Olympics'
];



An array could also be initialized using contructor. In the costructor format there are actually three different ways of initializing.

1. If you provide the constructor with 2 or more arguments, it will initalize the array elements.
2. If you supply only one argument to the constructor, it will initialize the length of the array - it does not initialize the elements of the array
3. If you do not supply any argument to the array, the elements are not initialized and the length is set to zero.

Look at the examples

var x = new Array(10,20,30,40,50)  // Array with 5 elements
var y = new Array(10)        //  Empty array of length 10
var z = new Array()           // Empty array of length 0