Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with var x = new Array();

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?

like image 823
Chris S Avatar asked May 19 '09 21:05

Chris S


People also ask

What does new array do in JavaScript?

The call to new Array(number) creates an array with the given length, but without elements. The length property is the array length or, to be precise, its last numeric index plus one.

Can a VAR be an array?

An array is a variable containing multiple values. Any variable may be used as an array. There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously.

How do you initialize an array in JavaScript?

You can initialize an array with Array constructor syntax using new keyword. The Array constructor has following three forms. Syntax: var arrayName = new Array(); var arrayName = new Array(Number length); var arrayName = new Array(element1, element2, element3,...


2 Answers

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.

like image 100
Dan Lew Avatar answered Sep 23 '22 05:09

Dan Lew


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

like image 23
Shog9 Avatar answered Sep 25 '22 05:09

Shog9