The literal notation avoids the single-argument pitfall or the Array global being redefined.
Use of the Array constructor to create a new array is discouraged in favor of array literal notation, i.e., [a, b, ...]
. The exception is when the Array constructor is used to intentionally create sparse arrays of a specified size by giving the constructor a single numeric argument.
Apply with the Grit CLI
grit apply no_array_constructor
Transform Array constructor to Array object.
BEFORE
Array(0, 1, 2);
AFTER
[0, 1, 2]
Transform Array constructor using new
to Array object.
BEFORE
new Array(0, 1, 2);
AFTER
[0, 1, 2]
Don't transform Array constructor.
JAVASCRIPT
Array(500);
Don't transform Array constructor using new
.
JAVASCRIPT
new Array(someOtherArray.length);