My understanding is destructuring like this will pick properties from the incoming argument object:
const last = "Smith" // unrelated const
const full = function({ first, last }) {
return [first, last].filter(v => v).join(" ")
}
full({last: "Doe"}) // "Doe"
full({}) // ""
And this seems to work the same for imports.
import last from "last"; // unrelated import
export function full({ first, last }) {
return [first, last].filter(v => v).join(" ")
}
full({last: "Doe"}) // "Doe"
full({}) // ""
Why then does this cause a no-shadow
eslint error?
error 'last' is already declared in the upper scope no-shadow
Is there any circumstance where full
could have access to the outer reference? No, right? How might I keep syntax close to this without renaming the unrelated outer last
reference?
Disallow variable declarations from shadowing variables declared in the outer scope.
When a variable in a local scope and a variable in the containing scope have the same name, shadowing occurs. Shadowing makes it impossible to access the variable in the containing scope and obscures to what value an identifier actually refers to. const a = 'no shadow'; function print() { console.
no-shadow should NOT error out on an object because object properties DO NOT act like variables in a new scope, so they CANNOT shadow a variable in the parent scope.
no-shadow should error out on an enum because enum properties act like variables in a new scope, so they can indeed shadow a variable in the parent scope.
The "extends": "eslint:recommended" property in a configuration file enables this rule Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.
The no-shadow rule helps to prevent a very common bug when using react-redux. That is, attempting to invoke the raw, unconnected action (which does not automatically get dispatched).
It's causing an eslint error because last
is declared in the import and in the the function as an argument. So inside the function, the argument last
is shadowing the import last
. You simply need to change the name of the parameter inside the function or turn eslint off.
import last from "last"; // unrelated import
export function full({ first, last: lst }) {
return [first, lst].filter(v => v).join(" ")
}
full({last: "Doe"}) // "Doe"
full({}) // ""
...or...
import last from "last"; // unrelated import
export function full({ first, last }) { // eslint-disable-line no-shadow
return [first, last].filter(v => v).join(" ")
}
full({last: "Doe"}) // "Doe"
full({}) // ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With