unicorn/no-useless-spread Correctness β
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
constructorWeakMap
constructorSet
constructorWeakSet
constructorTypedArray
constructorArray.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);
}