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?
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.
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.
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,...
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
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With