Today I stumbled on this javascript snippet.
var x = 5, y = 6;
x
++
y
alert (x + " " + y);
I would like to know why this doesn't throw a syntax error and more why y is 7 at the end? What is the use of this strange snippet if there are any at all?
Today I stumbled on this javascript snippet.
var x = 5, y = 6;
x
++
y
alert (x + " " + y);
I would like to know why this doesn't throw a syntax error and more why y is 7 at the end? What is the use of this strange snippet if there are any at all?
 
    
    This is due to automatic semi-colon insertion. Semi-colons are not optional in JavaScript. They simulate being optional by having the runtime add them for you.
The parser can only do so good a job at this. The basic algorithm is "if the line is a valid statement, then plop a semi-colon after it and execute it, if it's not, keep going onto the next line"
The parser turned that code into this:
var x = 5, y = 6;
x;
++
y;
alert (x + " " + y);
It's fashionable now to leave off semi-colons, but I still think that's a bad idea after years of coding in JS.
 
    
    I think, the cause is the Automatic Semicolon Insertion (ASI) of Javascript. The code is interpreted as follows:
var x = 5, y = 6;
x;
++y;
alert (x + " " + y);
