Skip to content

Latest commit

 

History

History
109 lines (85 loc) · 2.35 KB

File metadata and controls

109 lines (85 loc) · 2.35 KB

Disallow immediate mutation after variable assignment

💼🚫 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 Set or WeakSet from an array literal and immediately adding an new element with {Set,WeakSet}.add(…).
  • Assign variable to a Map or WeakMap from an array literal and immediately set another key with {Map,WeakMap}.set(…, …).

Examples

// ❌
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],
]);