understandinges6
understandinges6 copied to clipboard
Warn about accidentally destructuring to globals?
Hi Nicholas,
Location: Chapter 5 > Page 86 > "Destructuring Assignment" > first code block
Your examples all use destructuring in assigments (let or const), but it's also possible towards object properties, e.g.:
set fullName (value) {
[this.first, this.last] = value.split(' ')
}
And, more dangerously, seems to retain JS' long-standing wart of "accidentally" declaring globals when using hitherto-unknown identifiers without a declaration keyword ahead of them (agreed, strict mode would kill this, but we're not always in strict mode, unfortunately).
Do you think this would be a good warning to add somewhere in there?
By the way, you do mention it can destructure to object properties and existing vars, in the penultimate par on page 97, but it would be great to mention that in the original explanation, too.
Sorry, I'm not quite sure what you're asking here. Can you be more specific?
Sorry I was unclear. Let me try again.
Destructuring works in declarations (var, let, const), function signatures, and generally on the left side of assignments, which besides decls would include assigning to object properties and existing vars.
Your example code for this chapter focuses on declaration scenarios.
- On the one hand, I believe it would be a nice complement if the code and/or surrounding text also made other acceptable scenarios (e.g. obj props, existing vars) more obvious.
- On the other hand, declaration scenarios present the usual JS risk of people not understanding what happens when the declaring keyword (e.g.
let) is omitted. In strict mode, to be fair, this would throw. But loose mode will, as usual, create globals unbeknownst to the programmer. For instance:
function poorlyPickTwoProps (obj) {
{ foo, bar } = obj
return { foo, bar }
}
(yes, this would be much more nicely done by destructuring in the sig, bear with me :wink:)
Here, we unwittingly introduce two globals: foo and bar. This is a long-standing JS wart, and indeed people coming to JS tend to forget var or let sometimes, so perhaps warning them against this side-effect would be useful.
Is that clearer, or am I botching this again? 🤔