Both notations achieve the same result. Here are some advantages of using the []
notation:
- It is shorter.
- In case someone redefines the
Array
symbol, it will still work.
- There is no confusion when defining a single entry. For example, if you use
new Array(3)
, it could be misinterpreted as [3]
. In reality, it creates an array with a length of 3 and no entries.
- It may be slightly faster in certain JavaScript implementations because it doesn't require looking up the
Array
symbol like new Array
does. However, this difference is unlikely to have a significant impact in normal use cases.
Overall, there are several reasons to choose []
.
On the other hand, here are some advantages of using new Array
:
- You can specify the initial length of the array, for example:
var a = new Array(3);
However, I personally haven't found a need for this approach in years, especially after realizing that arrays aren't true arrays and pre-allocation is unnecessary. If needed, you can always achieve the same result by doing this instead:
var a = [];
a.length = 3;