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?
JSFiddle here
Syntax: a = ++x; Here, if the value of 'x' is 10 then the value of 'a' will be 11 because the value of 'x' gets modified before using it in the expression.
Python does not allow using the “(++ and –)” operators. To increment or decrement a variable in python we can simply reassign it. So, the “++” and “–” symbols do not exist in Python.
y++ is called post-increment -- it increments the variable after it returns the original value as the value of the expression. So x = y++;
The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. There is a plusplus option that prohibits the use of these operators.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With