51

In many situations, JavaScript parsers will insert semicolons for you if you leave them out. My question is, do you leave them out?

If you're unfamiliar with the rules, there's a description of semicolon insertion on the Mozilla site. Here's the key point:

If the first through the nth tokens of a JavaScript program form are grammatically valid but the first through the n+1st tokens are not and there is a line break between the nth tokens and the n+1st tokens, then the parser tries to parse the program again after inserting a virtual semicolon token between the nth and the n+1st tokens.

That description may be incomplete, because it doesn't explain @Dreas's example. Anybody have a link to the complete rules, or see why the example gets a semicolon? (I tried it in JScript.NET.)

This stackoverflow question is related, but only talks about a specific scenario.

Community
  • 1
  • 1

11 Answers11

73

Yes, you should use semicolons after every statement in JavaScript.

Adam Lear
  • 38,111
  • 12
  • 81
  • 101
  • 1
    If a language has certain cases where a semi-colon is required, I would take that and apply it to all cases if possible simply for the sake of code that is easier to read and code that simply looks good. So... +1. –  Jan 14 '09 at 18:17
  • 1
    For the sake of consistency and future readability, include semicolons after every statement. +1 – JustinT Jan 14 '09 at 18:30
  • 9
    Reasoned discussion is better than taking sides. – ShreevatsaR Jan 14 '09 at 18:30
  • 1
    See Crockford's reasons here: http://javascript.crockford.com/code.html "JavaScript allows any expression to be used as a statement. This can mask some errors, particularly in the presence of semicolon insertion." – Jordan Liggitt Jan 14 '09 at 18:36
  • 6
    Why hope that the JS interpreter will correctly guess your intentions (not just now, but with minor code changes) when you can just add the semicolon and communicate them unambiguously? – Andrzej Doyle Jan 14 '09 at 22:22
  • 4
    great article about js semicolons: http://mislav.uniqpath.com/2010/05/semicolons/ – makevoid Mar 17 '11 at 12:37
44

An ambiguous case that breaks in the absence of a semicolon:

// define a function
var fn = function () {
    //...
} // semicolon missing at this line

// then execute some code inside a closure
(function () {
    //...
})();

This will be interpreted as:

var fn = function () {
    //...
}(function () {
    //...
})();

We end up passing the second function as an argument to the first function and then trying to call the result of the first function call as a function. The second function will fail with a "... is not a function" error at runtime.

  • 2
    Wow, I always put a semicolon at the end of statements that look like `var foo = "bar";` but I did not know they should be at the end of functions, I thought the closing brace ended the statement? So should I put a semicolon after all block statements like `if`, `while`, etc. too? – JD Isaacks Feb 16 '11 at 21:41
  • 2
    @John: No. Note that my example involves an _assignment_ of a function. You don't need to -- and shouldn't -- put semicolons on regular functions or code blocks. –  Feb 18 '11 at 05:24
  • 5
    This is actually the _one_ example of where a newline cannot replace a semi-colon. I make a habit of any line that would start with ( to have a semicolon in front of it (so `;(function() {`) – Matt Briggs Aug 05 '11 at 01:37
  • Thanks for sharing this -- This exact use case happened when integrating code from two different sources. We figured out it could be fixed with a semi-colon pretty fast, but were unsure of the root cause. – chocojosh Apr 22 '12 at 20:31
16

Yes, you should always use semicolons. Why? Because if you end up using a JavaScript compressor, all your code will be on one line, which will break your code.

Try http://www.jslint.com/; it will hurt your feelings, but show you many ways to write better JavaScript (and one of the ways is to always use semicolons).

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 32
    If your javascript compressor can break your javascript code, I'd recommend using another one as soon as possible. – Alsciende Jun 07 '10 at 15:22
11

What everyone seems to miss is that the semi-colons in JavaScript are not statement terminators but statement separators. It's a subtle difference, but it is important to the way the parser is programmed. Treat them like what they are and you will find leaving them out will feel much more natural.

I've programmed in other languages where the semi-colon is a statement separator and also optional as the parser does 'semi-colon insertion' on newlines where it does not break the grammar. So I was not unfamiliar with it when I found it in JavaScript.

I don't like noise in a language (which is one reason I'm bad at Perl) and semi-colons are noise in JavaScript. So I omit them.

9

I'd say consistency is more important than saving a few bytes. I always include semicolons.

On the other hand, I'd like to point out there are many places where the semicolon is not syntactically required, even if a compressor is nuking all available whitespace. e.g. at then end of a block.

if (a) { b() }
8

JavaScript automatically inserts semicolons whilst interpreting your code, so if you put the value of the return statement below the line, it won't be returned:

Your Code:

return
5

JavaScript Interpretation:

return;
5;

Thus, nothing is returned, because of JavaScript's auto semicolon insertion

  • 15
    This is true, but is not at all relevant to the question. Explicitly using a semicolon would not help in this scenario. – Joel Anair Mar 06 '10 at 20:05
  • It would, as it would make the problem obvious on first sight of the code (alright more obvious, a true javascript programmer will consider it obvious without semicolons as well) – Jasper Jun 07 '10 at 14:52
7

I think this is similar to what the last podcast discussed. The "Be liberal in what you accept" means that extra work had to be put into the Javascript parser to fix cases where semicolons were left out. Now we have a boatload of pages out there floating around with bad syntax, that might break one day in the future when some browser decides to be a little more stringent on what it accepts. This type of rule should also apply to HTML and CSS. You can write broken HTML and CSS, but don't be surprise when you get weird and hard to debug behaviors when some browser doesn't properly interpret your incorrect code.

  • 1
    the difference is that broken html by definition doesn't conform to the spec. the javascript spec is very clear that semi colons are optional. http://mislav.uniqpath.com/2010/05/semicolons/ – Matt Briggs Aug 05 '11 at 01:28
  • Still omitting semicolons can lead to ambiguous statements, which as far as the compiler are concerned are not ambiguous, but for someone trying to read and parse the code in their head, very hard to parse without remembering a lot of specific rules. It's a lot more complex then new line = implied semicolon. http://news.ycombinator.com/item?id=374529 –  Aug 05 '11 at 12:48
6

The article Semicolons in JavaScript are optional makes some really good points about not using semi colons in Javascript. It deals with all the points have been brought up by the answers to this question.

5

This is the very best explanation of automatic semicolon insertion that I've found anywhere. It will clear away all your uncertainty and doubt.

1

No, only use semicolons when they're required.

Adam Lear
  • 38,111
  • 12
  • 81
  • 101
  • It's so much more beautiful. So why not? Ofc, it also implies to ALWAYS start your statement with ; when it is starting with (. So this line: (function(){ var iminvisible = 0 })() must have a ";" prepended, else you'll be in trouble. – odinho - Velmont Jan 18 '12 at 17:46
  • 1
    Read http://mislav.uniqpath.com/2010/05/semicolons/ :-) Oh, it was already in an answer here. – odinho - Velmont Jan 18 '12 at 17:46
1

I use semicolon, since it is my habit. Now I understand why I can't have string split into two lines... it puts semicolon at the end of each line.