💼🚫 This rule is enabled in the ✅ recommended config. This rule is disabled in the ☑️ unopinionated config.
🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.
When you create a variable and immediately mutate it, you should instead include those changes in the initial value.
- Assign variable to an array literal and immediately mutate with
Array#{push,unshift}(…). - Assign variable to an object literal and immediately assign another property.
- Assign variable to an object literal and immediately mutate with
Object.assign(…). - Assign variable to a
SetorWeakSetfrom an array literal and immediately adding an new element with{Set,WeakSet}.add(…). - Assign variable to a
MaporWeakMapfrom an array literal and immediately set another key with{Map,WeakMap}.set(…, …).
// ❌
const array = [1, 2];
array.push(3, 4);
// ✅
const array = [1, 2, 3, 4];// ❌
const array = [3, 4];
array.unshift(1, 2);
// ✅
const array = [1, 2, 3, 4];// ❌
const object = {foo: 1};
object.bar = 2;
// ✅
const object = {foo: 1, bar: 2};// ❌
const object = {foo: 1};
Object.assign(object, {bar: 2});
// ✅
const object = {foo: 1, bar: 2};// ❌
const object = {foo: 1};
Object.assign(object, bar);
// ✅
const object = {foo: 1, ...bar};// ❌
const set = new Set([1, 2]);
set.add(3);
// ✅
const set = new Set([1, 2, 3]);// ❌
const weakSet = new WeakSet([foo, bar]);
weakSet.add(baz);
// ✅
const weakSet = new WeakSet([foo, bar, baz]);// ❌
const map = new Map([
['foo', 1],
]);
map.set('bar', 2);
// ✅
const map = new Map([
['foo', 1],
['bar', 2],
]);// ❌
const weakMap = new WeakMap([
[foo, 1],
]);
weakMap.set(bar, 2);
// ✅
const weakMap = new WeakMap([
[foo, 1],
[bar, 2],
]);