Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this script increment y and not give a, for me expected, syntax error?

Tags:

javascript

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

like image 643
DarkBee Avatar asked Jan 18 '14 18:01

DarkBee


People also ask

What will be the correct syntax of increment function?

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.

Why does ++ not work in Python?

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.

What does ++ y'mean in JS?

y++ is called post-increment -- it increments the variable after it returns the original value as the value of the expression. So x = y++;

Is ++ OK in JavaScript?

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.


2 Answers

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.

like image 86
Matt Greer Avatar answered Oct 10 '22 10:10

Matt Greer


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);
like image 40
Thomas Junk Avatar answered Oct 10 '22 11:10

Thomas Junk