Writing semicolon-less JavaScript, the for-people-who-want-to-get-stuff-done edition
April 16th, 2012Semicolons at the end of statements (that is mostly end of lines) in JavaScript are optional. The specification calls this ASI, or “automatic semicolon insertion”, and is a bit obtuse about how exactly it applies (specifications tend to be written that way!).
So here’s the gist of what really matters for real-world JavaScript:
- At the end of a line, just don’t write a semicolon—it’s useless because JavaScript automatically interprets the line break as the end of the statement
- If your line starts with
(
or[
write a single semicolon before that—otherwise it’s interpreted as a function call or accessing a property (this situation will only rarely, if at all, happen in real-world JavaScript code)
So why would you do that? The answer is simple: it’s not needed. As a programmer, I’m glad about anything a language does for me automatically. I won’t have to think about this extra thing, and personally I find the code more readable as there’s fewer things to read and parse. Parsing and execution speed is the same, it’s not “error correction”, but just a language feature.
And that’s it. (There are some very specialized other cases, which for all intents and purposes are esoteric and academic. You can read up some more on this in Mislav’s excellent article).