New array syntax, several parameters

Using parenthesis notation, you can initialize an array with a zero or a large value:

var a= []; //length: 0, no items var a= [1]; //length: 1, items: 1 var a= [1,2]; //length: 2, items: 1,2 

Using new Array() , you can initialize an array with zero or two or more values:

 var a= new Array(0); //length: 0, no items var a= new Array(1); //length: 1, items: undefined var a= new Array(1,2); //length: 2, items: 1,2 

Referring to multi-parameter syntax, in JavaScript: the final guide , Flanagan writes:

Using an array literal is almost always simpler than using an Array () constructor.

He does not give examples in which a multi-parameter syntax is simpler, and I cannot come up with any. But the words "almost always" imply that there may be such cases.

Can you come up with something?

Please note that I understand the difference between these methods. My question in particular is: why do you need to use multiple parameter syntax with new Array() ? Flanagan suggests that there may be a reason.

+6
source share
3 answers

The only time you have to use new Array() with any parameters is the case of a single parameter in which you want to create an (empty) array of the specified length.

There is no other case where new Array() with any number of parameters (including zero) is preferred over an array literal.

In fact, an array literal should be used wherever possible, because although you can overwrite the Array() function so that it does something else (possibly malicious), it is impossible to undermine the syntax of the array literal.

+4
source

More simple, it probably refers to the fact that it is shorter, easier to write, more explicit, and you may have problems with things like:

 var test = new Array(1) //Empty array var test2 = [1] //not empty 
+2
source

I don’t think he meant that there are cases where using the syntax with several parameters is easier, but there are cases (only one that I can think of) where using the Array constructor is easier: creating an array of size N.

+2
source

Source: https://habr.com/ru/post/984440/


All Articles