unicorn/prefer-spread
Require the spread operator instead of Array.from(), concat(), slice() and toSpliced()
There are many ways to copy or join arrays: Array.from(items), items.slice(), items.slice(0), items.toSpliced(), items.concat(more). [...items] replaces all of them, and shows in one place what ends up in the new array.
--fix rewrites all of them except concat(), where the rule can't tell whether an argument is an array to spread or a single item.
Configure#
Off by default. To turn it on:
[lint.rules]
"unicorn/prefer-spread" = "error" # or "warn"Examples#
const links = Array.from(document.querySelectorAll("a"))Prefer the spread operator (...) over Array.from();
const copy = items.slice()Prefer the spread operator (...) over array.slice();
const sorted = scores.toSpliced()Prefer the spread operator (...) over array.toSpliced().sort();
const all = items.concat(more, last)Prefer the spread operator (...) over array.concat();const links = [...document.querySelectorAll("a")];
const copy = [...items];
const sorted = [...scores].sort();
const all = [...items, ...more, last];Calls that do more than copy aren't reported. Neither is slice() on a variable named buffer, arrayBuffer, blob or file, or concat() on a string or on a capitalized name such as Buffer:
const squares = Array.from(numbers, n => n * n);
const empty = Array.from({ length: 3 });
const rest = items.slice(1);
const chunk = blob.slice();
const greeting = "Hello, ".concat(user.name);
const body = Buffer.concat(chunks);When not to use it#
Spread needs an iterable. Array.from() also accepts an object that only has a length and indexes, so keep it for those.