JavaScript and added Semicolons

JavaScript has a feature that causes more problems to programmers than it helps, that is its automatic insertion of semicolons, if you happen to forget one.  Boo.

Almost all programming languages today, i.e. C, C++, C#, CSS, PHP, and Java to name a few, end a statement with a semicolon.  You know this, because your code won't run properly unless you put a semicolon in the right spot, at the end of your statement.  Javascript should do the same.

Javascript allows you to use as much white space as you want in making your JavaScript more readable. To do this, we put in lots of line breaks, instead of running a statement in one long line off to the right of the browser window.  You're allowed to omit semicolons in JavaSCript, so When JavaScript sees a line break, it may add a semicolon, to close your statement for you, and help you out.  This can cause unexpected errors.

To add to this helpful mess, JavaScript only adds semicolons in certain situations. So, JavaScript could easily drop in a semicolon, unbeknown to you, which will cause an error in your code.  This is a bug, that may not be easy to find, because its not visible in your code.

What are safe line breaks?  Where can you break the line without worrying about JavaScript's magic semicolons?

You can break a line:

1. After an arithmetic operator,
like: + - * / = == < >

Like so:

var candy_demand =
child + "at the candy store";

2. You can split a line after an opening
(, {, or [ or after a closing }.

This works:

if ( candy_demand ) {


Do NOT break a line:

1. After an identifier, value, or return keyword.


= meat + bone;

2. After a closing ] or )


bubble = ( gum + mouth )
+ (chew +blow);

3. Not after a return, continue, or break statement.



It will be taken as:
which is not what you want.

The "nots" above may not be easy to catch and will leave you scratching your head to figure out what went wrong.

Omitting semicolons is not a good idea.  You should always include them.  Just because JavaScript allows this, doesn't mean you have to use it.  Hopefully, in future versions this will be eliminated. What holds it up from being implemented is legacy code that may not have semicolons.  We have to bite the bullet at some point, better sooner then later.


JavaScript and added Semicolons — 1 Comment