Prefer the spread operator over Array.from(…), Array#concat(…), Array#{slice,toSpliced}() and String#split('')
💼 This rule is enabled in the ✅ recommended config.
🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.
Enforces the use of the spread operator (...) over outdated patterns. This also helps keep consistency by using a single flexible operator instead of:
Array.from(…)Convert
IterabletoArray.This rule adds on to the built-in prefer-spread rule, which only flags uses of
.apply(). Does not enforce forTypedArray.from().Array#concat(…)Concat an
Arraywith one or moreArray's orArrayelements.Array#slice()Shallow copy an
Array.Variables named
arrayBuffer,blob,buffer,file, andthisare ignored.Array#toSpliced()Shallow copy an
Array.String#split('')Split a string into an array of characters.
To enforce the spread operator over Object#assign(), use the built-in prefer-object-spread rule.
Fail
Array.from(set).map(element => foo(element));const array = array1.concat(array2);const copy = array.slice();const copy = array.slice(0);const copy = array.toSpliced();const characters = string.split('');Pass
[...set].map(element => foo(element));const array = [...array1, ...array2];const tail = array.slice(1);const copy = [...array];const characters = [...string];With the unicorn/no-useless-spread rule
Some cases are fixed using extra spread syntax. Therefore we recommend enabling the unicorn/no-useless-spread rule to fix it.
For example:
const baz = [2];
call(foo, ...[bar].concat(baz));Will be fixed to:
const baz = [2];
call(foo, ...[bar, ...baz]);unicorn/no-useless-spread will fix it to:
const baz = [2];
call(foo, bar, ...baz);