eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Rule proposal: Prevent returning/assigning mutating array methods

Open sindresorhus opened this issue 2 years ago • 4 comments

Description

Prevent returning or assigning mutating array methods, to improve readability and also protect against accidentally mutating an array in-place when you shouldn't. Array#sort(), Array#fill(), Array#reverse().

Fail

console.log(foo.sort());
const sorted = foo.sort();

Pass

foo.sort();
console.log(foo);
foo.sort();

I guess we should also allow the case where there's an intermediate array?

const sorted = foo.map(…).sort();

sindresorhus avatar Mar 01 '22 13:03 sindresorhus

Should only allow ExpressionStatement.

fisker avatar Mar 01 '22 14:03 fisker

Let's forbid Array#push()( covers #1487), Array#unshift(), Array#forEach()(unicorn/no-array-for-each already covered this, maybe people still prefer this method, but should only use as an ExpressionStatement), and Array#splice() too?

fisker avatar Mar 30 '22 12:03 fisker

Let's forbid Array#push()( covers https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1487), Array#unshift(), Array#forEach()(unicorn/no-array-for-each already covered this, maybe people still prefer this method, but should only use as an ExpressionStatement)

👍

, and Array#splice() too?

Hmm, a user may need the deleted elements.

sindresorhus avatar Apr 11 '22 09:04 sindresorhus

Accepted

sindresorhus avatar Jun 05 '22 09:06 sindresorhus