Settings

Theme

Semicolons in JavaScript are optional

mislav.uniqpath.com

31 points by sailormoon 16 years ago · 38 comments

Reader

axod 16 years ago

Use semicolons. Always. It's looks cleaner, and you won't come up against stupid errors like

  return
  {
     foo: 7
  }
From the article -

  When you're done trying to wrap your brain around
  why would anyone in their right mind want to write
  a return statement on a new line
Well, if they love having { on newlines, then it's pretty obvious:

  function foo()
  {
      return
      {
          bar: 8
      }
  }
From the article -

  That's 24 bytes right there. Stamp semicolons
  everywhere and run it through a minifier:

  var a=1;var b=2;var c=3;
Yeah um, hate to break it to you, but a minifier (and any experienced coder) would write it as "var a=1,b=2,c=3;"

  // after minification
  if(condition){stuff()}
Wrong again. Use a better minifier. Closure advanced mode for example will remove the {}, inline functions if it makes sense and hundreds of other things.

  Easy solution: when a line starts with parenthesis,
  prepend a semicolon to it.

  ;(d + e).print()
Ugly horrible hacky advice.

I remember when I first saw C code (coming from BASIC) and thought similar thoughts - eugh what are all those useless semicolons they don't do anything what's the point of them etc.

One important point is that it allows you to rearrange the whitespace in your code, without changing the execution meaning of your code. Which is pretty useful in making your code beautiful and readable and avoiding bugs.

  • danh 16 years ago

    I don't think semicolons help your example.

        return
        {
            foo: 7
        };
    
    still returns undefined.
    • axod 16 years ago

      And that's one of the reasons (IMHO) that bracketing style sucks.

      I was really explaining why rookies will make mistakes with js. The simplest way to prevent those types of errors is to always use ; and to use { on the same line style.

      • kls 16 years ago

        I understand the curly on the same line thing can bite you in Javascript, but man I find it so much easier to read when I can match them up by line of sight on a new line, that is one of my big pet peeves.

  • troels 16 years ago

    > It's looks cleaner, and ...

    I think my new pet-peeve is the word "clean". What you mean, when you say that, is that it looks good, according to your taste. That's a rather subjective statement, disguised as an objective one.

    (end of rant)

    • axod 16 years ago

      Yeah point taken. I guess what I mean here is that it removes ambiguity and separates logic (What the code is going to do) from display (How I like my source code laid out).

      I wasn't suggesting that languages that don't have semicolons look ugly or unclean. I do a lot of assembly language but obviously there is no real issue there with semicolon/line endings, since the convention is to write a single instruction per line.

  • peti 16 years ago

    The original argument is not about the minifier, but about semicolons. By the way, why would your better minifier introduce a semicolon here ? This is obviously a useless character in this example.

    Also, I don't understand how adding a semicolon could help against the "stupid error" you cite. Could anyone please explain ?

    • axod 16 years ago

      I don't actually remember what closure advanced mode does. It's quite possible it does remove ";" in some instances. But really, you either need a newline or a ";" to mark the end of a statement, so the question is fairly moot - it's gonna be 1 byte either way.

      If you always put semicolons to mark the end of a statement, then seeing a statement without one would be like seeing a megablocks brick in your lego box - glaringly obvious and extremely offensive.

      IMHO that backeting style sucks, and shouldn't be used, at least in js.

      • peti 16 years ago

        If you write one statement per line, the code is very clear, and there is no need for semicolons. It is after all possible, according to the syntax, and a minifier should be able to understand it, as well as your browser.

        I am certainly not against coding practices or readability. With (Q)BASIC, you could also add semicolons and have multiple statements per line, but who did ? It seems that it is the same with Javascript, semicolons are separators between statements, as well as newlines : why write both ? just to be sure they are well separated ?

        • axod 16 years ago

          it may be 'clear' to you, but as has been pointed out, it can be ambiguous as to what the code will do. The example with a line starting with an open bracket is one such example.

          Why force yourself to remember edge cases, when you can just remove that whole class of bugs by being explicit about what you mean...

travem 16 years ago

Do we really want to heed advice when it's comes with obviously wrong advice like "Only people can detect and solve software bugs, not tools."

Static bug analysis is definitely not the be all and end all of software quality but definitely has a place. We automatically run FindBugs (along with unit test etc) on our code base every time new code is pushed by a developer and it definitely helps pick up quirky little errors much more cheaply than code reviews.

jameskilton 16 years ago

I use semicolons, and a linter to let me know when I miss them, because IE pukes all over itself if I don't. Same with trailing commas, IE HATES those.

Article ignores reality.

  • lhorie 16 years ago

    I'd like to see an example of IE breaking without semi-colons. I've never seen that happen before. (I have seen the issue w/ commas though)

    • lhorie 16 years ago

      Why the downvote? A google search didn't turn up anything about a IE-only lack of conformance to the spec regarding semicolons.

      If you've seen code that breaks only IE because of a missing semicolon, please share.

weego 16 years ago

text on there made my eyes hurt.

the basic message seems to be "don't do what everyone else is doing just because everyone else does it".

Which is great in your bedroom, but in a team with lots of eyes on your code the most efficient way is to use the same style, with that style being one that is easy to read and that avoids potential misunderstandings and bugs.

I can't imagine any situation in the sphere of development this article is about in which worrying about a couple of hundred bytes is more important than having a set of code that someone other than yourself could happily sit in front of.

nixy 16 years ago

  I write semicolon-less code and,
  in my experience, there isn't a 
  JavaScript interpreter that can't 
  handle it.
Come visit me at work and I'll show you a few JS implementations on various set-top-boxes that will freak out if you don't use semicolons.
  • hackermom 16 years ago

    So in essence, the problem is still to be blamed on those specific JS implementations. Optional means optional, at which point making an implementation that demands the absence of semicolons is as bad as one explicitly requiring them, as both are breaking the set rule: optional.

    (personally, I'm for the mandatory semicolon, to avoid mistakes)

    • nixy 16 years ago

      Yep, those implementations are crappy, but they are in production and deployed in hundreds of thousands of end-user systems. The author seems to have only been testing PC web browsers, which is not the only place JS is used. This is easy to forget, though.

Tichy 16 years ago

The minifier he uses seems rather bad, wonder which one it was? Ie instead of var a = 1;var b=1; it could be var a=1,b=1; Also in case of the single line if, the minifier could actually remove the brackets.

mike-cardwell 16 years ago

His comments about minification are silly. It's entirely dependent on the minifier. Google Closure on my system converts:

if(condition) stuff()

To:

condition&&stuff()

So no, it doesn't add curly brackets and increase the size of the expression. And Google closure converts:

var a=1

var b=2

var c=3

To:

var a=1,b=2,c=3

Not what he said all minifiers do.

lzimm 16 years ago

Umm, please let me restate jameskilton's position below (http://news.ycombinator.com/item?id=1460474):

Use semicolons or your shit wont work in IE... That's why semicolons in javascript AREN'T optional.

subbu 16 years ago

What's wrong in using semicolons?

HendrikR 16 years ago

Simple question: Which code does preserve your lifetime? Highly optimized, less readable but really short code, or highly readable, good structured, better maintainable code? As for me, I really enjoy sharing my code with my colleagues. Maybe there are others who don't, but they always will have to work alone in the basement where light never reaches theirs pale faces (think of 'The IT Crowd', for example).

abp 16 years ago

Hm, if we look a little more generalized at what that says, its like:

"If theres a language/library feature with a few quirks, use it anyway, if the border cases aren't that usual."

Thats really bad advice. The main disadvantage is that no one will, if you combine a lot of such decisions, have all this border and special cases in mind, all the time.

earnubs 16 years ago

FWIW If you're using JavaScript in PhotoShop the following produces an error because there's no semicolon after the second statement:

  for(i=10;i--) { /* do stuff */ }
So maybe that's an example of a JS implementation where it differs on optional semicolons.
snitko 16 years ago

If you're so desperate about semicolons, maybe you should just use CoffeeScript instead?

TrevorBurnham 16 years ago

Gotta make a plug here for CoffeeScript, in which semicolons really are optional. CoffeeScript code compiles to neat, legible JavaScript (with semicolons).

http://coffeescript.org

RommeDeSerieux 16 years ago

I fail to see the problem with minification. The minificator can insert semicolons by itself because the algorithm for that is known and present in every JS engine. Besides, it just looks cleaner without them. Less for errors too.

phoboslab 16 years ago

The way this semicolon-free syntax is implemented should be reason enough not to rely on it: if the interpreter/compiler encounters an error, it steps back, inserts a semicolon and tries again.

maw 16 years ago

I bet this guy thinks using tabs in source code is a bright idea too.

seasoup 16 years ago

wow, quite the rant about... um... semicolons. yeah, ok, I only skimmed. much more interesting things out there.

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection