Thomas Fuchs
Hi, I'm Thomas Fuchs. I'm the author of Zepto.js, of script.aculo.us, and I'm a Ruby on Rails core alumnus. With Amy Hoy I'm building cheerful software, like Freckle Time Tracking and Every Time Zone and write books like Retinafy.me.
   Want me to speak at your conference? Contact me!

Writing semicolon-less JavaScript, the for-people-who-want-to-get-stuff-done edition

April 16th, 2012

Semicolons 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:

  1. 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
  2. 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).

Want to learn more about pragmatic JavaScript and using all the awesome language features in your code? Grab a seat at the JavaScript Master Class, a two half-day live online class with Amy Hoy and yours truly! (Next date: May 17/18, 2012!)