What are the best practices to follow when declaring an array in Javascript?
Mostly, people use var a = []
because Douglas Crockford says so.
His reasons include the non-intuitive and inconsistent behaviour of new Array()
:
var a = new Array(5); // an array pre-sized to 5 elements long
var b = new Array(5, 10); // an array with two elements in it
Note that there's no way with new Array()
to create an array with just one pre-specified number element in it!
Using []
is actually more efficient, and safer too! It's possible to overwrite the Array
constructor and make it do odd things, but you can't overwrite the behaviour of []
.
Personally, I always use the []
syntax, and similarly always use {}
syntax in place of new Object()
.
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.