The Truth About Semicolons in JavaScript

By  on  

There's been a lot of debate over semicolons in JavaScript.  Semicolons aren't required due to the nature of JavaScript's automatic semicolon insertion, but they've been been considered a best practice for years.  The following illustration sums up my thoughts on semicolon usage within JavaScript:

JavaScript Semicolons

Ultimately it's a team / organizational decision but consistency is key. Where do you sit on the JavaScript debate?

Image created by @rfunduk

Recent Features

Incredible Demos

  • By
    Scrolling “Agree to Terms” Component with MooTools ScrollSpy

    Remember the good old days of Windows applications forcing you to scroll down to the bottom of the "terms and conditions" pane, theoretically in an effort ensure that you actually read them? You're saying "No David, don't do it." Too late -- I've done...

  • By
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

Discussion

  1. Dan

    Just as long as one doesn’t accidentally forget that semicolons don’t actually do anything.

    I did this once:

    function() { return 
      1; }
    

    It didn’t end well. I was wondering why my function kept returning undefined. I ended up wrapping it like that because the function was passed as a parameter to another function call and it wrapped nicely that way. I fixed it by… not wrapping it like that.

    • Xiu
      function() { return 
        1; }

      I think that this piece of code will be converted by interpreter to

      function() { return ;
        1; }
    • Kim Helberg

      Yet another reason use the language as it was designed. Thank you, Xiu!

  2. Thank you!

    Improper usage of semicolons reminds me of txt spk. Just because it’s possible to read doesn’t make it right.

  3. Erik Lundmark

    It’s the price we pay for simplicity, which has proven to be complicated… You don’t see articles about these kind of quirks in the Python community f.i., but how much bigger is JS compared to Python? That said, inserting a semi-colon vs finding the error when U don’t? Worth it every time, if u know Why u’re using it. (Teams and large projects: another issue)
    Btw, thx for the Office Space remider, next on movie night :)

  4. Arpad Borsos

    Writing a semicolon is burned into my muscle memory pretty hard.
    I keep writing them in for (); loops which is kind of bad.
    Or I keep writing them in languages without them (python)

    Well that’s one downside of using a keyboard layout optimized for programming (neo2) :-)

  5. Stephen

    I have to put in the semicolons. It has been burned in to me since I started out with PHP, and in PHP if you forget a semicolon, nothing works.

  6. Lee Wilson

    I’d say definitely ALWAYS use them. Just because you can does not make it right. And I usually find it’s the lazy developers who do this!

    One major advantage for always using them is if you want to minify your JavaScript. If you do not use semi colons, and you minify (like a lot of developers like to do if their site serves a lot of JavaScript) you could get all sorts of problems.

    Such as:

    var myVar = 9
    if (myVar == 9) {
    
    }
    

    When minified, may become:

    var myVar 9 if (myVar == 9) {}
    

    And guess what? The script works unminified, but breaks due to a syntax error when minified, but if you drop in the semi colon where it should be, like this:

    var myVar 9; if (myVar == 9) {}
    

    It works :-)

    Moral of the story, don’t be lazy! And use them!

    • Nick

      Actually, the moral of the story you’ve just told is “don’t write tools that break otherwise working code.”

    • A proper minifier will process your JavaScript the same way the JavaScript engine does, thus making using semicolons or not worthless. It will insert the semicolons before minifying it.

      Let’s be honest here, there’s no excuse to or not to use semicolons. Pick one and stick with it. Code will work the same as long as you understand the gotchas of both sides.

      I use a linter, Standard by Feross that makes sure if I somehow do write code that would make the ASI trip up, it’ll be caught before it makes it that far. And even if I used semicolons, I’d use a linter, so don’t come back at me with “if you used semicolons you wouldn’t need a linter”

    • Mark Holtzhausen

      I could easily argue that it is in fact the lazy developers that insert semi-colons everywhere as they usually do so without even realising that the fundamentals of Javascript don’t require it. It is easier to just add them everywhere than to think about the code and omit it where it is sensible to do so.

      I prefer developers that actually think about the language they code in.

  7. Just use them. We all saw the debacle that unfolded in 2012 regarding Bootstrap and Crockford. If minimizing whitespace in your code causes it to behave differently, you’re doing something fundamentally wrong (unless your language relies on whitespace, of course).

    • Benjamin

      I’d say that if you write working code that a minimizer breaks, the minimizer is the component doing something fundamentally wrong ;)

    • Crockford wrote code that did not work the same way the JavaScript engine does, thus JSHint was wrong, not Bootstrap.

  8. I’d like to point out that the specification is clear about this. JavaScript’s syntactic grammar specifies that semi-colons are required. Omitting semi-colons results in invalid JavaScript code. That code won’t throw (thanks to ASI), but it’s still invalid. Again, the syntactic grammar is clear about this.

    • Kim Helberg

      Thank you! Your statement really ought to be the end of this mockery of a debate once and for all.

      The language uses semicolon to define the end of a statement. The fact that a tool for cleaning up mistakes (as well as an automated tool can) is ubiquitous doesn’t make the mistakes not-mistakes.

      Just like duct-taping plastic over a broken window doesn’t make the window not-broken.

  9. Codename: Steeve Knight

    Self-termination (unrelated to Swartzing [GBHS]) in ECMAScript necessitates using ;’s for best practice – ie mostly you’ll get away w/it but sometimes you won’t and may end up spinning your tired wheels.

    @note …and also ! dangling ones {‘s (which is just yucky looking).

  10. William Malo

    Personally, I find semicolons to be ugly and useless. The javascript language doesn’t need it, it’s only useful in these cases:

    var x,y,z;
    for(i=5;i--;)dostuff(),domorestuff(),dolastthing();

    It’s only used where you need to explicitly specify that the code ends.
    The only place where avoiding ;’s is a problem is when you use anonymous functions that run themselves, but if you have the habit of putting a ; before it, everything works.

    ;(function(){ ... })()

    Disclaimer:
    I have never worked with a team before.

    • Anonymous Coward

      Incorrect. Sir.

      See here on how IIFE’s (immediately invoked function expressions) work: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

    • Juliet

      Dear anonymous,

      Maybe “ugly and useless” is not the most enlightned reason to
      omit semi-colons, but I don’t see anything incorrect in William’s post.

      When you are avoiding semi-colons, you still need to put them as
      a guard before any lines that start with a ([+- character.

      See http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding

    • Kim Helberg

      Your “argument” is the only one I keep seeing against using semicolon. (Note that I put quotes around the word “argument” not to be an ass but because personal subjective opinion does not an argument make.)

      Excluding semicolon does nothing but assuage your personal sense of aesthetics.

      Including semicolon avoids a small but objectively real set of pitfalls and helps convey the author’s intent by removing ambiguity.

      Also..

      Taht msot peolpe can raed and unnderstad tihs deos not mkae for a plarticulary cnonvincig anrgumet in foavr of cnlaimig it is vilad Elgnsih.

  11. Good remainder for JS developers :) Thanks for the good mood

  12. What exactly is the benefit of NOT using them? Why even bother?

  13. I just put them.
    Usually I validate my code with JSLint and there I get warnings if I don’t add them.

    My opinion is to add them as it reduces the probability of having unexpected errors.

  14. I am in side where people think that semicolon should be there ;)

  15. Salman

    I always use them because I also code in other scripting languages where semicolons are required.

  16. I always use the semicolons, mostly due to the fact I come from C# and PHP background, and to me code looks way more readable with semicolons than without them.

    • Jon Galt

      I AVOID using them because I write in other languages. It’s particularly useful when you’re writing PHP code that manipulates Javascript code. (1) When I’m looking at my code, it’s more obvious which section I’m looking at. (I don’t want to spend one iota of brainpower figuring out what I’m looking at. It’s more fun to spend my time/brainpower developing and implementing algorithms.) (2) It actually makes the manipulation code easier.

  17. Juliet

    Where’s the blog post?

  18. Colon Semi

    Scores so far:

    [4] ALWAYS use them! I can’t explain exactly why…
    [3] I use semi-colons because I’m used to PHP/C/whatever
    [2] I’m used to them/don’t care
    [2] Just use the damn semi-colons!

    A pretty good technical discussion.

  19. PUT IN THE FUCKING SEMICOLONS!!!

  20. g23

    “What exactly is the benefit of NOT using them? Why even bother?”

    But, the real question is, what exactly is the benefit of using semi-colons? Why even bother [typing them]?

    There are NO valid technical arguments for or against them, they just don’t do anything.
    Imho, they are mere *decorative* elements, and as swiss/minimal design principles advocate should be removed ;-)

    • Kim Helberg

      Simple: Semicolons convey the intent of the author by removing ambiguity.

      The only argument against this that I’ve seen is that the amount of ambiguity removed is small. This is irrelevant, because however small it might be it’s still larger than zero, and any objective argument with a weight greater than zero is worth infinitely more than the personal preferences of some yahoo on the Internet. :P

      The alternative is leaving it up to code put in the JS-engines specifically as a crutch to beginner developers which ought to leave a bad taste in any programmer’s mouth.

  21. @g23

    that’s not correct, there are valid technical arguments for them – avoiding errors in certain situations, and linters. Whereas by using them, you will never risk getting those errors, and linters will work. A no brainer, IMHO

    For me it’s got to do mostly with muscle memory – I don’t want to stop at the end of each line and double check missing a semi colon will cause no trouble. it’s so much simpler and faster to type them every time.

    If you are really bothered by semicolons so much, just use CoffeeScript.

  22. Cazydi

    @g23 I do use them for my bookmarklets and removing extra 13h 10h characters from my compressed script.

  23. Jason

    Semicolons are optional like in PHP you have the option to use ‘<?' or '<?php' to start a block of code. Most of the time using either will work fine. There are some cases though where going against recommendations will bite you in the ass.

    In JavaScript the semicolon allows the developer to signify the end of a statement. This is very useful when it comes to minimising code. Without using semicolons you rely on JavaScript to figure it out for you. Often it will do a good job but not in 100% of cases. This is why it is always best to use semicolons.

  24. I am pretty obsessive about using them, probably because a bunch of languages that I used before JS made them mandatory.

    Use them and don’t risk errors, don’t use them and risk errors … a no brainer to me

  25. Forgetting semicolons now will frustrate you later when you attempt to be a better programmer and minify production code.

    enough said.

  26. Well coders like me who have been exposed to java,c++ etc before javascript tend to stick to the semi-colons . Also i tried this out in the mongodb shell(which is javascript based) :-

    var x=1 var y=2
    gives me SyntaxError :- Missing ; before statement

    while

    var x=1;var y=2 works just fine :D , So its better to include your semi-colons :)

  27. Idjits

    “Suppose I have code that works in every JavaScript implementation that I target (major browsers and some server-side implementations). If I run it through your minification tool and that tools breaks my code, then I’m sad to report that your tool is broken. If this tool edits JavaScript code, it’d better understand it as a real interpreter would.”

    Problem?

  28. JSHint.
    JSHint.
    JSHint.
    Use CodeKit and run check ‘run JSHint’ on every file. Fix the warnings and errors. Done.

  29. Let’s jshint or jslint – or whatever javascript lint do the job.
    Set up a jshintrc and let the tool do it’s job of taking care about code quality and syntax for the whole team :)

  30. Eljay

    I think Mislav clarified the semicolon discussion clearly in his web page http://mislav.uniqpath.com/2010/05/semicolons/

    I put the semicolons in. But I’m beginning to think that’s just because I’m used to C++, and I’m OCD.

    “…there are valid technical arguments for them…” but no valid technical arguments are forthcoming. Handwaving and F.U.D.

    Broken tools is not a valid technical argument. If your minifier does not handle semicolon-less code properly, it is a broken tool. There are many minifiers that are not broken.

    • Jonnybordo

      I’ve been reading about this debate today, and this is the third time I see people referring to this article.
      I just have to say that I think it’s a terrible article.
      It’s obviously biased, and at the end of it all he simply says: “I hate semicolons, it doesn’t help at all, oh except for that one case where you have to use it”.
      People using semicolons don’t need to think if it’s ok they’re using it or not, people who don’t do.
      I guess you can see on what side I am :)

  31. Karl

    If you want to leave them off. Don’t write JS, write CoffeeScript instead.

  32. I always put in semi-colons because I don’t want to think about whether I need one or not.
    I want to think about the feature I am delivering.

  33. Shneinerharven

    Better explicit than implicit right?

  34. Dawwg

    Like said before; the specs require it and not following them might break your code when refactoring, minimizing, so use them, otherwise you’re simply underperforming. If you have a car that has automatic emergency breaking and collission prevention, does that mean it’s smart or safe to simply not use the break at all anymore ???

  35. Niraj

    I would suggest to put semicolons, as it helps when you minify your js.

    • Jason F

      No it doesn’t… minifiers parse your code and use ASI as needed.

  36. Noopole

    You should put 2 semicolons at the end of each line… to be sure;;

  37. Semi-colons are a security blanket for thumb suckers.

  38. Newby

    I hate semicolons. I am a slow typer using a keyboard locale where semicolons are entered with shift+comma. This makes semicolons a bit more interruptive.
    This is even more true for curly braces. They are accessed via alt-gr-7 and alt-gr+0. In most countries curly braces and semicolons are typed with key combinations. I can write code without them much more fluently (e.g. Visual Basic).
    Unfortunately most programming languages were designed in the USA where type {, } and ; is easy.

  39. Anonymous

    Keep calm and just add the goram semicolon;

  40. I don’t use semicolons in my JavaScript, and I require my team to omit them too. Any code submitted that has semicolons will be rejected. Period.

    • Chris Hansen

      You reject code that adheres to the language specifications?

      Glad I’m not your manager – I hate filling out termination paperwork.

  41. I treat this like case-sensitivity.

    It’s cool that some languages are case-insensitive (VB) but when most are case sensitive you get into trouble if you start slacking in a language that lets you get away with it (not mattering) and then work in a lang where it does matter.

    Likewise semi-colons are required in java, PHP, and several other languages. Just because you “can get away with it” in **some** cases… in JavaScript you are asking for trouble if you start omitting them. I’d much rather be safe than sorry.

    There’s a great interview with Eric Lippert and the StackOverflow team (Jeff & Joel (before StackExchange)) https://blog.stackoverflow.com/2013/03/podcast-45-keeping-it-sharp/ mp3: http://www.podtrac.com/pts/redirect.mp3/feeds.soundcloud.com/stream/83835972-stack-exchange-stack-exchange-podcast-45.mp3

    That goes into detail the crazyness you (or your compiler) is faced with when you start getting flaky with the code you accept.

    I ensure that they are included in my JavaScript on all projects (except code-golfing exercises) and I’d probably refuse to work on a project that forced me to exclude them.

  42. maks

    quoting emca specs:

    11.9 Automatic Semicolon Insertion

    Certain ECMAScript statements ((*)…expression statement…) must be terminated with semicolons.

    all the statements listed in this point require a trailing semicolon to be valid statements.

    however, javascript ASI will insert it if missing when line-breaks are met (not always and sometimes when you would not expect…at least if you are new to the language). So you MAY chose omit them. ASI works as a code corrector and since we know how it works we can decide to use or not use semicolons. BUT valid statements listed in (*) at the end will havesemicolons.

    The following is valid javascript containing 2 lines of code:

    var a = 1
    var b = 2
    

    Nevertheless, those 2 lines of code are not valid javascript statements, but ASI (well the engine adopting EMCA and it’s ASI spec …. v8) will turn them into valid statements:

    var a = 1;
    var b = 2;
    

    You can choose to always use them or to omit them (being careful when the next line starts with “(“, “[“). Still, statements specified in 11.9 are valid only when they have have a final ; whether it’s you or ASI who puts it there.

    The reasons for a developer to type/omit semicolons are mostly related the personal programming background/experience. I come from C/C++/PHP so to me it’s natural to use them, and JS language syntax derives mainly from C.

    what i don’t understand is this correction:

    var a = 1
    var b = 2
    ;(a + b).toString()
    

    the beginning ; is needed because ASI in this case does not work as expected. Since it’s the preceding line of code that’s missing its semicolon, the normal correction would be to add it before the new line. But since adding it will make all other semicolon omissions weird, developers prefer to trick the corrector to make it work and so keeping the no-semicolon style at the end of any line. Instead of correcting the omission, we are tricking the ASI corrector.

    That another reason why my personal preference is to write js code with statements that are valid before ASI intervention.

    I daily use many wonderful js projects adopting the no-semicolon style guideline (well…who doesn’t) and i love them, but i agree with D. Crockford who considers ASI an “awful part” of javascript.

    :-)

  43. Waffles

    If nothing else, including semicolons wherever they belong provides consistency. My work projects currently all run on PHP and javascript, but I also work on personal projects in C#, still maintain some in Visual Basuck, and if I had more time I would revisit some old projects that are in C and C++. I do a lot of language switching, so it would be a waste of thought cycles if I had to stop and think, “Is this a language where I can get away with ommitting some semicolons? Is this a position where I can omit the semicolon?”

    To complicate matters further for me, I have inhereted a number of projects which had been written by super cheap, overseas labor. The use of line breaks and indentation was random and inconsistent, many varible names were non-sensical, and most of the code was just really bad and required rewriting. The only real consistency was that if a variable was misspelled, like “conpany” for “company”, all references to that variable were equally misspelled. Now whenever I see “weird looking” code like javascript missing semicolons at the ends of statements, my first thought is that I’ve received more crap code that I’m going to have to clean up.

    Another consideration is processing time. As web browsers continue to add to their feature sets, they’re getting more massive and more sluggish, and web applications are getting enormous. One commercial project I work on is so large that every time the team adds a large new feature, something slows done a little. (Before anybody accuses my team of writing pooprly optimized code, let me point out that other large sites like Facebook run like crap during the first few moments they’re loading.) My point is I can’t help but wonder if automatic semicolon insertion slows down javacript processing (when it’s initially loaded into the browser or ran through a minifier). This cost may seem insignificant, but in a very large project this can add up significantly. I cn omt vwls n sylbls 2 rit fstr n prob b undrstd but it taks lngr 2 red.

  44. Waffles

    Here’s a case why automatic semicolon insertion is detrimental:

    Yesterday I was looking at a string concatenation that was so long that it spanned a few line breaks for readability, and I realized that it was missing a “+” operator between the last two lines. Normally I would have expected this to cause an error because

    var blah = "string" "string";

    does not compute, but ASI put a semicolon where the missing “+” belonged, turning the last line into an inconsequential do-nothing string.

    Luckily nothing critical was impaired, but human error like this is not unusual, and a script interpreter should serve as a tool for flagging these kinds of errors so that they can be corrected.

  45. SomeNobody

    Personally I find any talk of convention brought from “other languages” a bit silly – such as “I use semicolons in JavaScript because I’m used to them from Java & PHP” – because JS isn’t Java or PHP…

    I think context is important – if you’re swapping “language” then you should also swap your conventions to match. I’m thinking along the lines of: When a French/English speaker wants to write “The Dog’s Bollock’s” in French as: “la chien de testicle” you don’t see “la chien’s de testicle’s” and then a following excuse of “because I uses apostrophies all the time in English; it must automatically apply for French…”

    Hopefully this provides some sort of example on my thoughts – merely using semicolons for the fun of it or because you’ve “done it before somewhere else” is false to presume this is the correct thing to do – if the excuse was “I’m using them wherever I feel they are applicable based on what the standards tell me” then this is by far the more sensible reason as to why one would use a semicolon to begin with…

    Just as a personal gloat, I can write in any language I like. I don’t consider myself a professional at them but I’m very comfortable with almost any ‘standard’ language (as in: no esoteric languages), but then I don’t assume ‘because indentation is used in Python that I should also use it in ASM, JS, PHP’ – I mean sometimes it looks nice to use it even when it isn’t strictly ‘needed’ but I take this into account when swapping between languages and regarding the standards that each one abides to…

    Knowing my luck I’m probably grave-digging this post, but as it gives me a way to actually post somethign without registering, I feel obliged to do so :D

    – Some Nobody

  46. Yeah[,] we don’t SAY the periods at the end of our sentences or the commas inside of them[,] but writing sentences without periods can be very confusing[.] A good editor will catch the missing periods and add them[,] just like ASI does with the semicolons[,] usually correctly but sometimes wrongly[.] An editor sometimes has to ask the author what they meant to fix a missing period or whatever and it’s unfortunate that ASI doesn’t provide the same feedback[.]

    Half of the art of programming (or possibly more) is making the most understandable code possible that still does what it’s supposed to do. I have not seen a single argument saying that leaving the semicolon off makes the code more readable, but there are a few arguments (unchallenged, I should point out) that semicolons make the code more readable.

    If you want to leave off the semicolons, would you also want to stop indenting? I don’t think so, and I submit that the same reason you wouldn’t applies to semicolons.

  47. I remember those day when I had to spend extra couple of hours of debugging due to missing semicolon.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!