1

This code runs as I expect:

let vw, vh
[vw, vh] = [document.body.clientWidth, document.body.clientHeight]
console.log(vw)

But this code doesn't. Just the unused assignment seems to change the behavior.

let vw, vh
const thebody = document.body  // what did I do wrong besides waste an assignment??
[vw, vh] = [document.body.clientWidth, document.body.clientHeight]
console.log(vw)

Weirder still, logging the body logs it, but causes an error on the next assignment...

 let vw, vh
 const thebody = document.body
 console.log(thebody) // what did I do EXTRA wrong besides log something??
 [vw, vh] = [document.body.clientWidth, document.body.clientHeight]
 console.log(vw)
danh
  • 62,181
  • 10
  • 95
  • 136
  • You're missing some semicolons – Pointy Sep 07 '20 at 16:15
  • Ooh. I think I'm about to learn something, @Pointy. I thought I could drop semicolons with impunity. I must be wrong? – danh Sep 07 '20 at 16:17
  • 1
    Yep :) `console.log(thebody)` followed by a newline is still an "open" expression, so the `[ ]` on the following line is considered to be a property access. – Pointy Sep 07 '20 at 16:17
  • 4
    Personally I don't like telling people what to do but I consider the proponents of "never bother with semicolons" to be misguided individuals. – Pointy Sep 07 '20 at 16:18
  • One reason why it’s not a good reason to blindly and blithely drop semi colon because “you could do it” – Terry Sep 07 '20 at 16:19
  • This is a nice piece of code to illustrate how people confuse 'Javascript will TRY to make sense of code which omits semi-colons' with 'Javascript will always work out what you meant'. They are not == – Toby Sep 07 '20 at 16:28

1 Answers1

3

For array destructuring assignment you need to include a semi colon before it...

const thebody = document.body; // Semicolon here
[vw, vh] = ...

... otherwise it is going to be interpreted as bracket notation of attempting to access a value in an object:

const thebody = document.body[vw, vh] = ...
Terry
  • 63,248
  • 15
  • 96
  • 118