Skip to content

unicorn/no-useless-spread Correctness

This rule is turned on by default.
⚠️🛠️️ A dangerous auto-fix is available for this rule.

What it does

Disallows using spread syntax in following, unnecessary cases:

  • Spread an array literal as elements of an array literal
  • Spread an array literal as arguments of a call or a new call
  • Spread an object literal as properties of an object literal
  • Use spread syntax to clone an array created inline

Why is this bad?

  • The following builtins accept an iterable, so it's unnecessary to convert the iterable to an array:

    • Map constructor
    • WeakMap constructor
    • Set constructor
    • WeakSet constructor
    • TypedArray constructor
    • Array.from(…)
    • TypedArray.from(…)
    • Promise.{all,allSettled,any,race}(…)
    • Object.fromEntries(…)
  • for…of loop can iterate over any iterable object not just array, so it's unnecessary to convert the iterable to an array.

  • yield* can delegate to another iterable, so it's unnecessary to convert the iterable to an array.

Example

javascript
const array = [firstElement, ...[secondElement], thirdElement];
const object = { firstProperty, ...{ secondProperty }, thirdProperty };
foo(firstArgument, ...[secondArgument], thirdArgument);
const object = new Foo(firstArgument, ...[secondArgument], thirdArgument);
const set = new Set([...iterable]);
async function foo() {
  const results = await Promise.all([...iterable]);
}
for (const foo of [...set]);
function* foo() {
  yield* [...anotherGenerator()];
}
function foo(bar) {
  return [...bar.map((x) => x * 2)];
}

// Pass

const array = [firstElement, secondElement, thirdElement];
const object = { firstProperty, secondProperty, thirdProperty };
foo(firstArgument, secondArgument, thirdArgument);
const object = new Foo(firstArgument, secondArgument, thirdArgument);
const array = [...foo, bar];
const object = { ...foo, bar };
foo(foo, ...bar);
const object = new Foo(...foo, bar);
const set = new Set(iterable);
async function foo() {
  const results = await Promise.all(iterable);
}
for (const foo of set);
function* foo() {
  yield* anotherGenerator();
}
function foo(bar) {
  return bar.map((x) => x * 2);
}

References

Released under the MIT License.