2

I've just found a decent bug in my JS code, which I'm porting from C++:

var x = "aaa"
        "bbb";

//In C++: x="aaabbb" 
//In JS: x="aaa" 

Surprisingly there were no error (in node.js).

How does JS handle "bbb"?

Valentin H
  • 7,240
  • 12
  • 61
  • 111
  • 1
    arguably you're seeing a silent error, but in JS, it's not a formal error to have orphan expressions. – dandavis Jun 29 '15 at 01:01
  • 1
    In c++ (and c) a new line is considered a concatination (as in your case the silent char \\), in javascript it is considered a new line. – Jobst Jun 29 '15 at 01:02

3 Answers3

3

Semi-colons are not required in javascript to end a statement. Those statements were interpreted as set x to "aaa" and execute next statement "bbb" which is just an arbitrary string.

You can think of it as the semi-colon being auto inserted so the statements become

var x = "aaa";"bbb";
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • OK, thanks! Have to keep this in mind. Actually the string was an ´SQL DELETE´ expression , where "bbb" was the ´WHERE´ part :-( – Valentin H Jun 29 '15 at 01:24
2

JavaScript is inserting a semicolon after the first line.

So, what you're really doing is

var  x = "aaa";
         "bbb";

It evaluates the first line, which assigns "aaa" to x and then evaluates the second line which doesn't assign "bbb" to anything.

You might want to see this question about the rules for semicolon insertion in JS

Community
  • 1
  • 1
Luke
  • 5,567
  • 4
  • 37
  • 66
2

It doesn't handle it. What happens is that JavaScript will insert a semicolon for you, and "bbb" is merely an expression:

var x = "aaa"; // JS inserts this semicolon
"bbb"; // this is a valid expression but does nothing

This feature is known as ASI. If you put a + it will concatenate the strings:

var x = "aaa" +
        "bbb";
elclanrs
  • 92,861
  • 21
  • 134
  • 171