Reputation: 7448
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"?
Upvotes: 2
Views: 60
Reputation: 30597
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";
Upvotes: 3
Reputation: 94121
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";
Upvotes: 2
Reputation: 5708
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
Upvotes: 2