org.sonar.l10n.javascript.rules.javascript.S1528.html Maven / Gradle / Ivy
Why is this an issue?
Array literals should always be preferred to Array constructors.
Array constructors are error-prone due to the way their arguments are interpreted. If more than one argument is used, the array length will be
equal to the number of arguments. However, using a single argument will have one of three consequences:
- If the argument is a number and it is a natural number the length will be equal to the value of the argument.
let arr = new Array(3); // [empty × 3]
- If the argument is a number, but not a natural number an exception will be thrown.
let arr = new Array(3.14); // RangeError: Invalid array length
- Otherwise the array will have one element with the argument as its value.
let arr = new Array("3"); // ["3"]
Note that even if you set the length of an array, it will be empty. That is, it will have the number of elements you declared, but they won’t
contain anything, so no callbacks will be applied to the array elements.
For these reasons, if someone changes the code to pass 1 argument instead of 2 arguments, the array might not have the expected length. To avoid
these kinds of weird cases, always use the more readable array literal initialization format.
Noncompliant code example
let myArray = new Array(x1, x2, x3); // Noncompliant. Results in 3-element array.
let emptyArray = new Array(); // Noncompliant. Results in 0-element array.
let unstableArray = new Array(n); // Noncompliant. Variable in results.
let arr = new Array(3); // Noncompliant; empty array of length 3
arr.foreach((x) => alert("Hello " + x)); // callback is not executed because there's nothing in arr
let anotherArr = arr.map(() => 42); // anotherArr is also empty because callback didn't execute
Compliant solution
let myArray = [x1, x2, x3];
let emptyArray = [];
// if "n" is the only array element
let unstableArray = [n];
// or, if "n" is the array length (since ES 2015)
let unstableArray = Array.from({length: n});
let arr = ["Elena", "Mike", "Sarah"];
arr.foreach((x) => alert("Hello " + x));
let anotherArr = arr.map(() => 42); // anotherArr now holds 42 in each element