Wednesday, June 19, 2013

ghost semicolons in JavaScript

Building on this, I learned today that the reason to not have a line break between an open curly bracket and the thing opening it in JavaScript lies in the reality that the semicolon is optional as terminator in JavaScript and that when it is left off (intentionally or unintentionally) that JavaScript may assume a termination when there is some ambiguity as to whether or not a termination should be. You may cut the ambiguity by just putting open curly braces on the same line as their openers. Please do so. If you do not you run the risk of authoring something like this...

return
{
   "foo":"bar", "baz":"qux"
}

 
 

...which ends up being interpreted with a ghost semicolon like so:

return;
{
   "foo":"bar", "baz":"qux"
}

 
 

Spooky!

Share photos on twitter with Twitpic

No comments:

Post a Comment