understandinges6 icon indicating copy to clipboard operation
understandinges6 copied to clipboard

Warn about accidentally destructuring to globals?

Open tdd opened this issue 8 years ago • 3 comments

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?

tdd avatar Jan 25 '17 16:01 tdd

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.

tdd avatar Jan 25 '17 16:01 tdd

Sorry, I'm not quite sure what you're asking here. Can you be more specific?

nzakas avatar Jan 25 '17 17:01 nzakas

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? 🤔

tdd avatar Jan 25 '17 19:01 tdd