Do you recommend using semicolons after every statement in JavaScript?
Asked Answered
S

11

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.

Stroboscope answered 14/1, 2009 at 18:14 Comment(0)
S
73

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

Stroboscope answered 14/1, 2009 at 18:14 Comment(6)
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.Babble
For the sake of consistency and future readability, include semicolons after every statement. +1Symphonist
Reasoned discussion is better than taking sides.Jackdaw
See Crockford's reasons here: 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."Nobell
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?Disserve
great article about js semicolons: mislav.uniqpath.com/2010/05/semicolonsMarcelmarcela
G
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.

Gaffe answered 14/1, 2009 at 18:14 Comment(4)
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?Orme
@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.Stroboscope
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() {)Aufmann
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.Avitzur
S
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).

Stroboscope answered 14/1, 2009 at 18:19 Comment(1)
If your javascript compressor can break your javascript code, I'd recommend using another one as soon as possible.Inearth
S
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.

Stroboscope answered 14/1, 2009 at 18:14 Comment(0)
S
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() }
Stroboscope answered 14/1, 2009 at 18:14 Comment(2)
In that particular case you save a few bytes and use a semicolon with if (a) b;Plain
modern compressors will insert semicolons mislav.uniqpath.com/2010/05/semicolonsAufmann
S
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

Stroboscope answered 14/1, 2009 at 18:14 Comment(2)
This is true, but is not at all relevant to the question. Explicitly using a semicolon would not help in this scenario.Papilloma
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)Allred
S
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.

Stroboscope answered 14/1, 2009 at 18:14 Comment(2)
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. mislav.uniqpath.com/2010/05/semicolonsAufmann
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. news.ycombinator.com/item?id=374529Stroboscope
S
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.

Stroboscope answered 14/1, 2009 at 18:14 Comment(0)
G
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.

Gaffe answered 14/1, 2009 at 18:14 Comment(0)
U
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.

Unanimity answered 14/1, 2009 at 18:14 Comment(0)
S
1

No, only use semicolons when they're required.

Stroboscope answered 14/1, 2009 at 18:14 Comment(2)
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.Cemetery
Read mislav.uniqpath.com/2010/05/semicolons :-) Oh, it was already in an answer here.Cemetery

© 2022 - 2024 — McMap. All rights reserved.