Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

It seems to be fashionable recently to omit semicolons from Javascript. There was a blog post a few years ago emphasising that in Javascript, semicolons are optional and the gist of the post seemed to be that you shouldn't bother with them because they're unnecessary. The post, widely cited, doesn't give any compelling reasons not to use them, just that leaving them out has few side-effects.

Even GitHub has jumped on the no-semicolon bandwagon, requiring their omission in any internally-developed code, and a recent commit to the zepto.js project by its maintainer has removed all semicolons from the codebase. His chief justifications were:

  • it's a matter of preference for his team;
  • less typing

Are there other good reasons to leave them out?

Frankly I can see no reason to omit them, and certainly no reason to go back over code to erase them. It also goes against (years of) recommended practice, which I don't really buy the "cargo cult" argument for. So, why all the recent semicolon-hate? Is there a shortage looming? Or is this just the latest Javascript fad?

share|improve this question
2  
"years of recommended practice" refer a question of blacklisted SO polls tag which unlikely makes it authoritative to support any kind of opinion –  gnat Mar 29 '12 at 12:42
18  
@gnat just because people hate the question being on SO doesn't make it a less valid source of people's opinion. –  Ryathal Mar 29 '12 at 12:58
    
@Ryathal it's not about hate - eg, I wouldn't mind if OP referred to particular answer of that question that I could study - but this is not what I see. OP simply gives question link as if this automagically makes their statement authoritative - to which I object by pointing out that questions of that kind are officially considered inappropriate at SO. Fair enough? –  gnat Mar 29 '12 at 13:27
2  
@gnat Questions that are "officially considered inappopriate on StackOverflow" are sometimes considered very authoritative by the expert community. Sad but true. –  MarkJ Apr 4 '12 at 17:15
2  
@gnat The blacklisted question actually has some very interesting examples of why omitting the ; can break your code. So I'd say it's a useful reference for this question. –  Andres F. May 13 '13 at 12:22

12 Answers 12

up vote 22 down vote accepted

I suppose my reason is the lamest: I program in too many different languages at the same time (Java, Javascript, PHP) - that require ';' so rather than train my fingers and eyes that the ';' is not needed for javascript, I just always add the ';'

The other reason is documentation: by adding the ';' I am explicitly stating to myself where I expect the statement to end. Then again I use { } all the time too.

The whole byte count argument I find irritating and pointless:

1) for common libraries like jquery: use the google CDN and the library will probably be in the browser cache already

2) version your own libraries and set them to be cached forever.

3) gzip and minimize if really, really necessary.

But really how many sites have as their biggest speed bottleneck the download speed of their javascript? If you work for a top 100 site like twitter, google, yahoo, etc. maybe. The rest of us should just worry about the code quality not semicolon religious wars.

share|improve this answer
    
I guess the opposite could be true as well. As python becomes more popular for web it's easier to have your JS resemble python. –  Ben DeMott Mar 31 '12 at 8:37
1  
Try but then the same byte warriors would be after me for unnecessary whitespace at the beginning of lines. ( I would also have Javascript bugs because I would rely on Python's indent rule rather than using { } –  Pat Apr 1 '12 at 11:21
3  
If reducing byte count is important, you'll have something that minimizes the files as much as possible. If it isn't worth using a minimizer yet, then it isn't worth worrying about removing ';' to save on byte count. –  Lawtonfogle Apr 16 at 20:07
1  
byte count isn't actually necessarily reduced, in-fact it can actually be increased as a new-line is often (not always) actually two characters (new-line followed by carriage-return) so in its most space efficient form the new line will be once character same as a one character semi-colon (if you compact all your JS code in one line which is often done for the deployed JS code, not the development source code). –  ALXGTV May 30 at 17:46

I recently wrote a parser/analyzer for JavaScript, where I had to painstakingly implement ASI, and I also have my copy of Crockford's JavaScript: The Good Parts on my bookshelf, which advocates always using semicolons. The intention was good, but it doesn't always help in practice.

Obviously, the people writing frameworks like jQuery, zepto, etc. are JavaScript syntax masters and thus they know the difference between:

return
{
    status: true
};

and

return {
    status: true
};

JavaScript, while powerful, is also a beginner's language and good luck explaining this to someone who is just learning what a for loop is. Like introducing most people to a new skill, there are some more complex things you don't want to explain right away, so instead you choose to instill a "cargo cult" belief in certain things just to get them off the ground. So, you have two choices when teaching a beginner how to write JavaScript:

  1. Tell them "follow this one rule and don't ask why", telling them to put a always semicolon at the end of every line. Unfortunately, this doesn't help in the example in the above, or any other example where ASI gets in the way. And Mr. or Ms. beginner programmer gets befuddled when the code above fails.
  2. Tell them "follow these two rules and don't ask why", telling them not to bother with semicolons at the end of every line, and to instead always a) Follow return with a {, and b) When a line starts with a (, prepend it with a ;.

Choosing option 2 is a better set of "cargo cult" rules to follow (will result in very few ASI-related bugs), and even if you do get a deep understanding of the topic, you have fewer unneeded characters on the screen.

share|improve this answer
5  
All right, I'll bite. Help me understand the difference in syntax between the two examples above. My untrained eye only sees a difference in formatting. –  Jesse C. Slicer Mar 29 '12 at 20:27
6  
Or, on the other hand, I stumbled across the answer by sheer accident. In the first example, the return is considered a solitary statement and the line-end is the equivalent of a semicolon. The second example actually returns the object. Tricksy. –  Jesse C. Slicer Mar 29 '12 at 20:30
7  
I don't think I can agree with the idea that JavaScript is a beginners language, there are tons of inconsistencies and surprise effects in JavaScript that don't have simple explanations. IMO a beginners language wouldn't be like that, I would call JavaScript an intermediate language. –  Ryathal Mar 29 '12 at 20:32
4  
Clarifying point: the return example is actually an exception to the normal JS behavior which is to attempt to pull lines together when a semi-colon is omitted. return, break, and continue all exhibit this exceptional behavior in which a trailing newline is always interpreted as an end of statement. (Source is Flanagan's "JavaScript: The Definitive Guide" pp25-26). Personally, I strive for the idea of "code of least surprise." Leaving semi-colons out tends to result in more surprises than anything (I generally also keep my curly braces even for simple statements). –  Kyle May 13 '13 at 16:58
2  
This answer concerns placement of {, not semicolons. I fail to see how it is relevant to OP. Though it is an objective argument in the eternal bracket holy war. –  user949300 Dec 3 '14 at 9:16

semi colons in JavaScript are optional

My personal reason for not using semi colons is OCD.

When I use semi colons I forget 2% of them and have to constantly check / add them back in.

When I don't use semi colons I never accidentally put one in so I never have to check / remove them.

share|improve this answer
1  
Good one. I've been burned by a semicolon-less line or two in an otherwise properly semicoloned file. –  Jonathan Mar 29 '12 at 12:59
1  
There are parsers (e.g. GeSHi) that will not parse your code correctly if semicolons are not present. You could say that humans will not make such mistakes... But seriously - event if all of your team will manage to remember where semicolons absolutely need to be put, do you really think they will remember it without morning coffee? And they will code in many states of minds. Be sure of it. –  Nux May 11 '13 at 17:08

It makes method chaining easier and commit diffs cleaner

So let's say I'm jQuerying about and I have

$('some fancy selector')
  .addClass()
  .attr();

If I want to add stuff and keep my line-based commit diff small, I have to add it above attr. So it's one thought longer than just "add at the end". And who wants to think? =)

$('some fancy selector')
  .addClass()
  // new method calls must go here
  .attr();

But, when I drop the semi-colons, I can just append and call it a day

  $('some fancy selector')
    .addClass()
    .attr()
+   .animate()
+   .click()

Also, if I decide to pop off the last method, I don't have to reassign the semi-colon and pollute my commit again.

  $('some fancy selector')
    .addClass()
    .attr()
    .animate()
-   .click()

Versus the uggo

  $('some fancy selector')
    .addClass()
    .attr()
+   .animate();
-   .animate()
-   .click();
share|improve this answer
8  
This is niche use case IMO. –  JBRWilkinson Mar 29 '12 at 22:30
2  
But interesting nevertheless. –  Jonathan Mar 30 '12 at 11:30
4  
You can have semicolon at the end on a new line indented as the starting line. Then you copy and reorder things as you wish. This also closes the chain nicely. –  Nux May 11 '13 at 17:38
6  
Is it just me who wonders why anyone would care how neat the diffs of their commits look? as a general rule, people read code, not diffs. –  Jules Dec 3 '14 at 12:06
2  
I may be a bit of an extremist but I like my diffs looking as neat as possible. This is similar to including whitespace or formatting changes in a feature commit; it's a distraction from what really needs to be code reviewed. I look at diffs all the time during code reviews. –  Mark Canlas Dec 3 '14 at 19:07

Choosing a programming convention is effectively the same as choosing subset of the target language. We all do this for the usual reasons: code readability, maintainability, stability, portability, etc. -- while potentially sacrificing flexibility. These reasons are real business reasons.

Reasons such as "saving keystrokes," and "programmers should learn the JavaScript rules" are marginal business reasons so they carry little practical weight.

In my case I needed to come up to speed in JavaScript very fast, so leveraging a limited subset of the language was to my advantage. So I chose the JSLint subset of JavaScript, turned on the Rockstar apps JSLinter in Eclipse to the most restrictive settings I could stand, and haven't looked back.

I'm grateful to be able to avoid the details of the difference between "==" and "===", or the details of semicolon insertion, because I've got a mile high task list already and those details won't help get those jobs done one second earlier.

Of course the most important thing about a convention is consistency, and thinking of it as a language subset helps to reinforce this imperative. And although this may not help answer the OP's question, I think it might help with the practical framing of it.

share|improve this answer

There’s no such thing as information overload, only bad design.

— Edward Tufte

It's a general rule in graphic design to leave out unnecessary elements and ornamentation to reduce noise.

Fewer visual elements on the screen means less work for our brains to parse the actual useful information.

let foo = 1

vs.

let /* variable */ foo = 1; // EOL

An exaggerated example of course, but it illustrates the general principle: Additional visual elements should be added if and only if they serve a purpose. So, do semicolons serve a purpose?

The historical reasons to use semicolons in JavaScript were:

  • Maintain similarity to C / Java
  • Avoid compatibility issues with poorly written browsers and tools
  • Helping humans and machines detect code errors
  • Automatic Semicolon Insertion carries a performance penalty

The compatibility issues are pretty much a non-issue today. Modern linters can detect any code errors just as well without semicolons. Similarity with C/Java/PHP can still be a consideration (see the accepted answer by Pat), but just because other languages contain superfluous syntax elements does not mean we should keep them in JavaScript, especially since many other languages (Coffeescript, Python, Ruby, Scala, Lua) do not require them.

I did a quick test to see if there was a performance penalty in V8. This is Io.js parsing a 41 MB JavaScript file (Lodash repeated 100 times) with semicolons and then with semicolons removed:

$ time node lodashx100.js
node lodashx100.js  2.34s user 1.30s system 99% cpu 3.664 total
$ time node lodashx100s.js
node lodashx100s.js  2.34s user 1.15s system 99% cpu 3.521 total

Everyone has to decide their own preferred coding style for their projects, but I no longer see any tangible benefit in using semicolons, so to reduce visual noise, I've stopped.

share|improve this answer

I have two theories:

A)

The thing about this choice is that back in the day, when JSLint etc. were applicable, you were choosing to spend a large amount of time catching obscure syntax errors, or a reasonable amount of time enforcing a standards policy on code.

However, as we move more towards Unit Test-driven code and continuous integration the amount of time (and human interaction) required to catch a syntax error has decreased massively. Feedback from tests will quickly indicate if your code is working as expected, well before it gets near an end-user, so why waste time adding optional verbosity?

B)

Lazy programmers will do anything to make their own lives easier in the short term. Less typing -> less effort -> easier. (also, not having to semicolon will avoid straining your right-hand ring-finger, avoiding some RSIness).

(N.B. I disagree with the idea of omitting something that disambiguates a statement).

share|improve this answer
    
jshint is still an important tool. –  Raynos Mar 29 '12 at 16:40
    
As for disambiguating a statement, both \n and ;\n are the same –  Raynos Mar 29 '12 at 16:41
    
@Raynos Actually, I've found that JSLint tends to be a bit useless with the complexity of some of the framework-heavy code I often work with. Plus, ;\n and \n aren't the same in all circumstances, otherwise there'd never be a need for the ;. –  Ed Woodcock Mar 29 '12 at 16:48
5  
jslint is useless, jshint however is a different tool. –  Raynos Mar 29 '12 at 17:09

I don’t leave them out, but i change the rules when to insert them.

The rules most people use is

  • Before each line ending
  • Except the line ends with a } coming from a function statement
  • But only a function statement, not assignment to a function literal

My rule is: At the beginning of every single line starting with a opening brace/bracket.

Mine is simpler, therefore easier to follow and less prone from bugs. Also the low number of semicolons makes it easy to find bugs made by leaving it out.


Another argument is that the infamous return\nvalue bug comes from not knowing about ASI. My rule forces you to know about ASI, so people using my rule are less likely to fall into the trap of that bug.

share|improve this answer

Quite an old question, however I'm surprised no one has mentioned:

Minification: If you happen to minify a JavaScript snippet that doesn't explicitly end the statements with a semi-colon character, you might end up having a hard time trying to figure out what is wrong with a snippet that was just working before the minification and now doesn't work.

Ambiguity: Semi-colons are optional, true, however by eliminating them from the source-code, you might leave some ambiguous scenarios to the parser to decide on its own. If you are writing a 100 lines of code for an online shop, yes, maybe it doesn't matter, but more serious tasks would require a 100% clarity.

Long time ago I read a very nice analogy about something else but it's very true in this case also: (In our case) Eliminating the semi-colons is like crossing at a red light. You might be okay in the end or you might get hit by a truck.

Why it's becoming more popular these days?

I personally believe having JavaScript runs on the server-side had a lot of effects on the JavaScript community itself. In our case, obviously no one is going to minify the JavaScript on the server-side (as the source-code is not supposed to ship to the client's web browser), so having no semi-colons looks much safer which is true; however the other developers who learn from these books, articles and videos, they unfortunately dismiss the fact that JavaScript on the server-side is not exactly the same as JavaScript in the client-side.

share|improve this answer
    
Minifiers could leave in single-character newlines or insert semi-colons when semi-colons aren't present without a size penalty. I don't know which (if any) minifiers do this. The danger still exists in at least some of them, so your point still holds in practice. –  outis Jul 12 at 23:25

There are good reasons to keep them in.

They are not really optional, JS can add them back in with automatic semicolon insertion when they are missing but that is not the same thing.

Douglas Crockford's JavaScript: The Good Parts says on two separate occasions that it is a bad idea. The automatic semicolon insertion can hide bugs in your program and creates ambiguity.

JSLint doesn't approve.

share|improve this answer

Byte count. You see, malicious people usually try to fit so much into a single line of code. Technically speaking, this would not be possible without semi-colons. My supposition is that it is more of a security measure than just a programmatic requirement. Somehow, this would significantly reduce XSS when it becomes a requirement rather than a suggestion.

share|improve this answer
1  
"I keep forgetting where where the semi-colon lies on my keyboard" So your inability to learn the keyboard layout should be used as a justification for causing possible extra headache for the next programmer to maintain the code? (Remember: The maintenance programmer who has to fix something in your code is a violent psychopat who knows where you live.) –  Michael Kjörling Apr 16 at 12:38
    
That wasn't my whole reason, Michael. I'm only appreciating the change, which has to take place once in a while. And anyway, what was the purpose of having the semi-colons, when lines were automatically terminated by new lines? –  Trouble Zero Apr 16 at 12:44
    
Omitting semi-colons will have no affect on parse or execution time. –  outis Jul 12 at 23:08

JavaScript hasn't needed semi-colons to terminate statements in over a decade. That's because newline characters are considered statement terminators(I believe this is also mentioned in early ECMAScript specs). It really makes a lot of sense, especially since there really is no good reason [that I know of] why JavaScript would need frequent use of semi-colons but not other interpreted declarative languages like Ruby or Python.

Requiring semi-colons may make it easier to write a parser for a language, but if every interpreter out there supports the omission of semi-colons then what exactly is the point?

What it comes down to is how knowledgeable a programmer is: if you know that you can omit a semi-colon, feel free to do so understanding that there may or may not be a consequence. Human beings are decision-making machines and nearly all decisions require some compromise or trade-off. The trade-off to just throwing semi-colons all around your code(even in places where they aren't needed) is that your code becomes less read-able(depending on who you ask) and JSLint won't complain(who cares). On the other hand, the trade-off to omitting semi-colons is the fact that 90% of JavaScript programmers will chastise you for it, but you may end up enjoying writing JavaScript more because of it.

What sounds better to you; making informed decisions or blind decision-making / herd-mentality?

share|improve this answer
    
I'd be interested to know why this has received downvotes. JavaScript doesn't need semi-colons to terminate statements; it can certainly use them, but they are by no means a requirement. If they were needed, then nobody else's explanations would work. The fact(yes, a fact) that you can write an entire JavaScript application with few to no semicolons demonstrates this. Beyond that, I don't see how understanding how a tool works and using one's own reasoning to make decisions is somehow objectionable in contrast to "just do it". That's what's known as religion. –  Ravenstine 2 days ago

protected by gnat Aug 27 at 4:29

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.