prefer-const: Bug that says variable is never reassigned, when is it
JadsonLucena opened this issue · comments
What version of this package are you using?
17.0.0
What operating system, Node.js, and npm version?
Debian 11
Nodejs v19.7.0
NPM 9.5.0
What happened?
The following error is reporting when it shouldn't: {variable} is never reassigned. Use 'const' instead prefer-const
What did you expect to happen?
Actually, it shouldn't report any errors.
Are you willing to submit a pull request to fix this bug?
Yes
how to replicate the bug:
class User {
#name
#age
constructor (name, age) {
let errors = []
try {
this.name = name
} catch (err) {
errors.push(err)
}
try {
this.age = age
} catch (err) {
errors.push(err)
}
if (errors.length > 1) {
throw new AggregateError(errors, 'Invalid User')
} else if (errors.length === 1) {
throw errors[0]
}
}
set name (name) {
if (typeof name !== 'string' || !name) {
throw new TypeError('Invalid name')
}
this.#name = name
}
get name () {
return this.#name
}
set age (age) {
if (!Number.isFinite(age) || age < 1) {
throw new TypeError('Invalid age')
}
this.#age = age
}
get age () {
return this.#age
}
}
expect:
// AggregateError: Invalid User
try {
new User(false, false)
} catch (err) {
console.error(err)
}
// TypeError: Invalid name
try {
new User(false, 'bar')
} catch (err) {
console.error(err)
}
// TypeError: Invalid age
try {
new User('foo', false)
} catch (err) {
console.error(err)
}
// User {#name: 'John Doe', #age: 18}
try {
new User('John Doe', 18)
} catch (err) {
console.error(err)
}
We found that in at least three cases the 'errors' array receives new items, but the eslint always returns: 'errors' is never reassigned. Use 'const' instead prefer-const
In JavaScript, const
doesn't mean deep immutability, but rather that the binding will always point to the same thing. In this case the errors
binding is always pointing to the same array, and then that array is being mutated.
Thus the errors
binding is never reassigned, and const
is appropriate to use here...