Thursday, July 7, 2011

javascript semicolon insertion

I mentioned javascript semicolon insertion in my post: But I think this topic deserves more attention.

In javascript, semicolon is optional. We better understand how javascript handles a statement without a semicolon at the end.

Usually, if javascript cannot parse the code without a semicolon, it will treat the line break as a semicolon. Let's check this code:

var name

Javascript will interpret the code as:

var name;
name = 'henry';

Since javascript cannot parse the code: var name name, it treats the line break of 'var name' as a semicolon, therefore it is just as 'var name;'. Javascript can parse the code: name = 'henry', so it does not insert a semicolon at the end of the name statement.

So the general rule is that javascript will treat a line break as a semicolon if the next non space character cannot be parsed as a continuation of the current statement.

This awful rule can cause awful result, for example:

var a = 3, b=5;
var func = function(v)
    return v+10;
var f = func

Javascript interprets the code as: var a = 3, b=5; var func = function(v) { alert(v); return v+10;}; var f = func (a+b).toString(); console.log(f);
See the code  var f = func (a+b).toString()? that is probably not what you want. 

That is not the end of the story yet. There are two exceptions to the general rule. The first is about 'return', 'break' and 'continue' statements. Javascript always interpret their line breaks as semicolons. So, if we have:


Javascript will parse it as return; {}; instead of return {}; The second exception is ++/-- operation. For example:
Javascript read the code as x; ++y; instead of x++; y; 

The best practice in writing javascript code is we should always remember to put semicolon at the end of a statement. Don't rely on javascript's awful mechanism.

No comments: