jeudi 18 juin 2015

JavaScript without semi colon

As I like programming in Python, using a language that force me to put a semi colon at the end statements bother me a lot. As you may know, the semicolon to end a statement is optional in JavaScript. And you may also know that forgetting it when you need it can hurt you badly.

It turns out that the exceptional cases that prevent the interpretor to consider that a \n is not enough to end a statement are rather simple. Isaac Schlueter recalls them:

In general, \n ends a statement unless:

  1. The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with . or ,.)
  2. The line is -- or ++ (in which case it will decrement/increment the next token.)
  3. It is a for(), while(), do, if(), or else, and there is no {
  4. The next line starts with [, (, +, *, /, -, ,, ., or some other binary operator that can only be found between two tokens in a single expression.

Actually, the most annoying is the 4th one when the next line starts with a paren since it can break immediately-invoked function expressions. But you can easily avoid that in your code with a prefix:

;(function x() { do_sth() })()

Or even:

!function x() { do_sth() }()

Because hey, ExpressionStatements cannot start with function key word.

If you want to respect others code, it might be reasonable to end your file with a semi colon.

This discovery made my day, and I started writing JavaScript code without semi colon with confidence. It's cool.