Declaring Arrays

3. Array() Constructor Method


          The arrays are represented by the Array object in JavaScript. A special constructor called Array() is included in the Array object that provides another way to create an array. A constructor is a particular type of function that is used to establish reference variables as the basis for (that is, variables whose data type is the reference data type). You can create new arrays with the constructor Array() by using the new keyword and the constructor Array() name with the following syntax:


or


          You include an integer that represents the number of elements to be included in the array inside the parentheses of the Array() construction.

 Example1:              

<script>

//creating array with constructor method

var chemElements = new Array(4);

chemElements[0] = "Argon";

chemElements[1] = "Krypton";

chemElements[2] = "Neon";

chemElements[3] = "Xenon";

//accessing the values of array

document.write(chemElements[0]+"</br>");

document.write(chemElements[1]+"</br>");

document.write(chemElements[2]+"</br>");

document.write(chemElements[3]+"</br>");

</script> 

Example2:

 The code below will generate the same output as the methods above.

<script>

//creating array with constructor method

var chemElements = new Array("Argon", "Krypton", "Neon", "Xenon");

 //accessing the values of array

document.write(chemElements[0]+"</br>");

document.write(chemElements[1]+"</br>");

document.write(chemElements[2]+"</br>");

document.write(chemElements[3]+"</br>");

 </script>



          In general, JavaScript programmers create arrays using literals instead of the constructor. Many programmers think it's better to use literals than to use the constructor, and the constructor provides no unique advantages over literals.