1 2 3 4 5 6 7 8
Fair enough. Lately i’ve been doing more and more ruby. Ruby is a language universally praised for its elegant, easy to read syntax. One of the strong points of the syntax is its terseness, that is, you can omit a lot of punctuation. Semicolons as well. Wait a moment…
1 2 3 4 5 6 7 8
Removing semicolons and other punctuation clutter is not just a liability. It actually makes your code look better.
1 2 3 4 5 6 7 8 9 10 11
It’s safe because how a line is parsed depends on the line itself, not by other lines that could be written “by others”. The bad part is how it makes method chaining on multiple lines look ugly. This is why ruby 1.9 introduced the exception “the statement continues if the first character of next line is a dot”.
1 2 3 4 5
Unfortunately, you now have a nasty problem. 2 lines which are supposed to be 2 different statements, but with the first character of the second line being a valid continuation of the first, will be treated as one statement with unpredictable results. This practically happens only when a line starts with either ( [ + - /
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
To write semicolon-free code and avoid getting bitten, you just need to remember 2 rules:
- Don’t put an end-of-line between return, break, continue, throw, postfix ++, postfix – and their operand
- Avoid starting a line with ( [ + - / but if you have to, prepend it with a semicolon
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Is it that taxing to remember? Automatic semicolon insertion is of course controversial, but using it is not a complete failure. It’s a matter of taste, a trade-off between cleaner nicer code and some tough albeit avoidable pitfall.
While i’m at it, let’s debunk some well known myths that always show up
“It’s not gonna work the same way on every browser” It’s in the specs since more than a decade. I think browser bugs are a thing of the past and even proponents of this theory look unable to find something newer than 5 years ago, so.
“It breaks the tools. You cannot minify code anymore, etc…” Let’s be clear about this. It’s officially part of the language. A tool unable to cope with ASI is a broken tool, period. Anyway, i have never had a problem with google closure compiler.
“Jslint doesn’t work with it” Jslint enforces the vision of Douglas and it’s pretty strict about it. This is fair, yet for those having another vision nothing is wrong with using Jshint which has an option to accept ASI.
Let’s close with two very nice articles that explain the details and of course you can always read the ecmascript specs: