views:

870

answers:

5

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?

+1  A: 

u earned 7 bytes ;)

Tolgahan Albayrak
+27  A: 

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.

Daniel Lew
could you give an example?
TStamper
Good point! Note that overriding Array will also lead to serious problems in code that attempts to use Array.prototype methods on array-like objects such as arguments... So still a very bad idea.
Shog9
Not only that, but the Array() constructor has some "odd" behaviour depending on how many arguments you pass it. It's just generally quirky and best avoided.
Dominic Mitchell
Don't get me wrong, I'm most certainly not promoting overriding Array. (Well, not unless you override 'undefined' and 'NaN' as well, just to screw with anyone who would ever dare use your code.)
Daniel Lew
If you override Array, what happens to var x = []; That is an Array object is it not?
Chris S
[] will always be an Array object. When I say "override", I don't mean to imply that the actual Array class is overridden. "Array" is actually a global variable, and as such can be assigned a new value - so I'm reassigning what the variable "Array" references. What Array used to reference is still intact. (This is also why I joke about overriding 'undefined' and 'NaN' as well - they, too, are global variables that can be manipulated in this same, twisted way.)
Daniel Lew
+11  A: 

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....

Shog9
However, jslint breaks when you try to initiate an array with n values. For instance: var x = new Array(20); This method of creation isn't used often, but it has its cases and is much faster than using a loop to create and populate an array.
digitala
You can just set the n'th element to undefined and it does more or less the same thing
mikelikespie
+2  A: 

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.

Rudd Zwolinski
Why was this downvoted?
musicfreak
probably because w3 schools is not associated w3.org and they often have poor or inaccurate code.
Andrew Austin
+3  A: 

Nothing wrong with either form, but you usually see literals used wherever possible-

var s='' is not more correct than var s=new String()....

kennebec