Why is the semicolon output of this js code different?

var a = 1
var b = 2
[a, b] = [b, aqb]
console.log (a, b)

var a = 1;
var b = 2;
[a, b] = [b, afib]
console.log (a, b)

Why is the output different in the console without adding semicolons and semicolons?
my personal habit of never adding a semicolon before, does it mean that this habit is bad?

Jan.23,2022

if there is no semicolon and no ASI mechanism, it is equivalent to

var a = 1
var b = 2[a, b] = [b, a+b]
console.log(a, b)

and 2 [a, b] equals undefined , [b, aqb] equals [undefined, 1 + undefined], then assigns a value from right to left, and the final value of b is [undefined, NaN]

.

adding a semicolon is the basis for adding a broken sentence, and the above code becomes

.
var a = 1;
var b = 2;[a, b] = [b, a+b]
console.log(a, b)

because the second line of code is no longer interpreted as a continuous assignment, b is assigned to 2 first, and then according to deconstruction, and the final result is [2,3]

< hr >

updated
about 2 [a, b] Why is equal to undefined , because this is obviously the syntax of array evaluation. The specific evaluation order is as follows:

  • a, b is first evaluated by the comma operator, which evaluates from left to right and returns the value of the last expression, so the value of a, b represents undefined
  • 2 [undefined] equals undefined

you enter the above code line by line instead of copying it as a whole, which has the same effect as the following code. When you write code in IDE, whether you add a semicolon or not can have the same effect because of the ASI mechanism.

The ASI mechanism in
JavaScript allows us to omit semicolons. The ASI mechanism does not mean that the parser automatically adds the semicolon to the code in the parsing process, but that the parser will use the semicolon as the basis for breaking sentences according to certain rules on the basis of line breaks, so as to ensure the correctness of the parsing.

it is recommended to add a semicolon. Not only for myself to change bug, refactoring, debugging, etc., but also to make team cooperation more efficient in the future

Menu