unicorn/prefer-spread

Require the spread operator instead of Array.from(), concat(), slice() and toSpliced()

fixable

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:

bunfig.toml
[lint.rules]
"unicorn/prefer-spread" = "error" # or "warn"

Examples#

example.js4 problems
const links = Array.from(document.querySelectorAll("a"));
const copy = items.slice();
const sorted = scores.toSpliced().sort();
const all = items.concat(more, last);
example.jsNo problems
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:

example.jsNo problems
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.