Avoid new Array()

There is no need to use the JavaScript's built-in array constructor new Array(). Use [] instead. These two different statements both create a new empty array named points:

   var points = new Array();  <== Bad
   var points = [];  <== Good

These two different statements both equally create a new array containing 6 numbers:

   var points = new Array(40, 100, 1, 5, 25, 10)  <== Bad
   var points = [40, 100, 1, 5, 25, 10];  <== Good

As mentioned earlier in this tutorial, the new keyword complicates your code and produces nasty side effects. You can create an array with multiple elements, but if you create a new array with only one element, you will get a whole different situation:

HTML file: Displayed by browser:
<body>
<h4>Using new Array with two items:</h4>
<p id="demo"></p>
<hr />
<h4>Removing one item from the new Array:</h4>
<p id="demo1"></p>
<script>
var points = new Array(40, 100); // Creates an array with two elements
document.getElementById("demo").innerHTML = points[0];
var points = new Array(40); // Creates an array with 40 undefined elements !!!!!
document.getElementById("demo1").innerHTML = points[0];
</script>
</body>

Using new Array with two items:


Removing one item from the new Array:


BackTable of ContentsNext