In JSLint, it warns that
var x = new Array();
(That's not a real variable name) should be
var result = [];
What is wrong with the 1st syntax? What's the reasoning behind the suggestion?
In JSLint, it warns that
var x = new Array();
(That's not a real variable name) should be
var result = [];
What is wrong with the 1st syntax? What's the reasoning behind the suggestion?
It's safer to use []
than it is to use new Array()
, because you can actually override the value of Array
in JavaScript:
Array = function() { };
var x = new Array();
// x is now an Object instead of an Array.
In other words, []
is unambiguous.
Crockford doesn't like new
. Therefore, JSLint expects you to avoid it when possible. And creating a new array object is possible without using new
....
There's nothing wrong with the first syntax per se. In fact, on w3schools, it lists new Array()
as the way to create an array. The problem is that this is the "old way." The "new way", []
is shorter, and allows you to initialize values in the array, as in ["foo", "bar"]
. Most developers prefer []
to new Array()
in terms of good style.
Nothing wrong with either form, but you usually see literals used wherever possible-
var s='' is not more correct than var s=new String()....