Use the literal syntax for array creation.
ESLint: no-array-constructor
⇣ Incorrect code for this rule:
const snow = new Array();
⇡ Correct code for this rule:
const snow = [];
Use Array#push
instead of direct assignment to add items to an array.
⇣ Incorrect code for this rule:
const winter = [];
winter[snow.length] = "snow";
⇡ Correct code for this rule:
const winter = [];
winter.push("snow");
Use array spreads ...
to copy arrays.
⇣ Incorrect code for this rule:
const winter = ["snow", "frost"];
const winterCopy = [];
let idx;
for (idx = 0; idx < winter.length; idx += 1) {
winterCopy[idx] = winter[idx];
}
⇡ Correct code for this rule:
const winter = ["snow", "frost"];
const winterCopy = [...winter];
Use spreads ...
instead of Array.from
to convert an array-like object to an array.
⇜ Avoidable code for this rule:
const winter = document.querySelectorAll(".snow");
const nodes = Array.from(winter);
⇢ Recommended code for this rule:
const winter = ["snow", "frost"];
const nodes = [...winter];
Use Array.from
instead of spread ...
for mapping over iterables. This avoids creating an intermediate array.
⇣ Incorrect code for this rule:
const winter = ["snow", "frost"];
const winterMap = [...winter].map(seasons);
⇡ Correct code for this rule:
const winter = ["snow", "frost"];
const winterMap = Array.from(winter, seasons);
Use return statements in array method callbacks. This excludes functions that consists of a single statement returning an expression without side effects.
ESLint: array-callback-return
⇣ Incorrect code for this rule:
// No returned value means `winter` becomes undefined after the first iteration.
[
[0, 1],
[2, 3],
[4, 5],
].reduce((winter, element, index) => {
const flatten = winter.concat(element);
winter[index] = flatten;
});
seasons.filter((season) => {
const { name, element } = season;
if (name === "winter") {
return element === "snow";
} else {
return false;
}
});
⇡ Correct code for this rule:
[1, 2, 3].map((num) => {
const snow = num + 1;
return num * snow;
});
[1, 2, 3].map((num) => num + 1);
[
[0, 1],
[2, 3],
[4, 5],
].reduce((winter, element, index) => {
const flatten = winter.concat(element);
return flatten;
});
seasons.filter((season) => {
const { name, element } = season;
if (name === "winter") {
return element === "snow";
}
return false;
});
Use line breaks after open and before close array brackets if an array has multiple lines.
⇣ Incorrect code for this rule:
const arr = [
[0, 1], [2, 3], [4, 5]
];
const objectInArray = [{
id: 1
}, {
id: 2
}];
const numberInArray = [
1, 2
];
⇡ Correct code for this rule:
const arr = [
[0, 1],
[2, 3],
[4, 5],
];
const objectInArray = [
{
id: 1,
},
{
id: 2,
},
];
const numberInArray = [
1,
2
];