1

Please, someone cound explain this behavior with and without semicolon?

Without semicolou, it raise a ReferenceError: Cannot access 'b' before initialization

let a = 1
let b = 2
[a,b]=[b,a]

It's ok with semicolon:

let a = 1;
let b = 2;
[a,b]=[b,a]

It doesn't occurs using var.

  • The two snippets are identical. Semicolons should not make any difference here. – anatolhiman Aug 15 '21 at 23:23
  • Without the semicolons, the last two lines become `let b = 2[a,b]=[b,a]`. You will get the same error if you try `let b = [b, a]`, which doesn't throw an error with `var` because of var declaration hoisting, which doesn't happen with `let`. – Mark Aug 15 '21 at 23:26
  • It does matter in this case, and it's the second semi-colon that is required to avoid a parsing error – danh Aug 15 '21 at 23:26
  • first expression with `var` does not throw an error but does not work as expected. `a` is set to `1`, but `b` is set to `[undefined, 1]`. – Vitalii Aug 15 '21 at 23:30
  • 1
    also see: [When is it dangerous to line break after a close parenthesis in Javascript?](https://stackoverflow.com/questions/3721784/when-is-it-dangerous-to-line-break-after-a-close-parenthesis-in-javascript) – pilchard Aug 15 '21 at 23:31

1 Answers1

2

This line, without semicolons, evaluates to let b = 2[a,b..., and since b is being declared in the same expression, it throws the error. Adding a semicolon after the 2 will remove the attempted index and resolve the error.

Mark
  • 90,562
  • 7
  • 108
  • 148