When I need to declare a new array I use this notation
var arr = new Array();
But when testing online, for example on jsbin, a warning sign
One significant difference is that []
will always instantiate a new Array, whereas new Array
could be hijacked to create a different object.
(function () {
"use strict";
var foo,
bar;
//don't do this, it's a bad idea
function Array() {
alert('foo');
}
foo = new Array();
bar = [];
}());
In my example code, I've kept the Array
function hidden from the rest of the document scope, however it's more likely that if you ever run into this sort of issue that the code won't have been left in a nice closure, and will likely be difficult to locate.
Disclaimer: It's not a good idea to hijack the Array
constructor.
The speediest way to define an array or object is literal way, because you don't need to call the constructor
var arr1 = new Array(1, 2, 3, 4);
var arr2 = [1, 2, 3, 4];
alert(arr1[0]); // 1
alert(arr2[0]); // 1
var arr3 = new Array(200);
var arr4 = [200];
alert(arr3[0]); // 'undefined'
alert(arr4[0]); // 200
It's because new Array()
is ambiguous. These are the correct constructors:
// Using brackets
[element0, element1, ..., elementN]
// Using new AND a list of elements
new Array(element0, element1, ..., elementN)
// Using new AND an integer specifying the array length
new Array(arrayLength)