7 ms·
Ask HN: Why use semicolons to terminate statements in modern JavaScript or ActionScript?
I hope the question doesn't come across as flamebait, because I'm genuinely interested in the response here. My background is mainly in the largely semicolon-less Python and Ruby. This may have impeded my understanding of the issues involved. :^)
ECMAScript-derived languages have inherited many syntactical conventions of C-style languages (e.g. braces to demarcate blocks). However, while semicolons are required to terminate a statement in C-style languages like Java, they are optional in modern variants of Javascript and Actionscript, where a line feed is considered to imply a semicolon if the statement on that line is complete.
Being able to leave out semicolons is blissful as far as I'm concerned. When coding in Java, I frequently run into compiler errors because I have neglected to type a semicolon, whereas I can't think of a single time when omitting semicolons in Javascript or Actionscript has caused me problems.
However, the code style of others (e.g. website Javascript, or Actionscript open source projects) suggests that my opinion mustn't be widely held; I see semicolons everywhere.
Now, Javascript on a web site has to run in many different browser environments, and I can understand how fear of incompatibility could keep coders locked to semicolons (although like I say, I haven't seen any browser problems myself). But Actionscript gets compiled, removing the uncertainty about how syntax will be interpreted on the client. So why are semicolons still being used now that they are optional in Actionscript 3.0? Do semicolons provide a secret benefit that I'm not aware of?
- illumen 18y agothey allow copy/paste with other C syntaxish languages edit: Sorry, I forgot to include caps, and full stops for that first sentance.
- timknauf 18y agoHah, do I detect a little light jab in your lack of punctuation? I guess it partly depends on how you view the relationship between programming languages like Javascript and the typographical conventions of natural languages like English. I tend to think of a series of statements in a programming language as more akin to a to-do list of imperatives than a paragraph from a recipe book. If you are writing a to-do list, you don't need to mark the end of the instruction; the end of the line functions for this purpose. Something like this would be sufficient for understanding: break eggs into pan fry the eggs remove the eggs from pan eat the eggs As opposed to the recipe approach: Break the eggs in the pan; now fry the eggs; next remove the eggs from the pan; now eat the eggs. More syntactical marks are required for clarity (including many semicolons!), but the first approach (the to-do list) is arguably closer to how code is actually written.
- MaysonL 18y agoor in Factor or Forth: : pan egg break-in fry remove eat ;
- shutter 18y agoTwo areas that I can come up with: 1. Minification -- If you want to minify your JS, you might run into problems if you don't insert all necessary semicolons. 2. Convention -- If you wrote js code with no semicolons and then showed it to other JS programmers, you'll get a funny look, a slap in the face, or a free copy of "Javascript for Dummies", depending on the context.
- timknauf 18y agoHmm, I hadn't considered the minification context - good point. That said, doesn't HTTP compression make minification largely unnecessary? As for convention: yes, I have indeed had some funny looks when asking this question in real life (no slaps yet, though). If you're working in a team, you obviously need to conform to one coding style; I'm coming from a mostly sole-coder perspective. But why does the convention persist? (Is that a strange question to ask?) Is it simply the weight of tradition, or are there other benefits?
- neilk 18y agoDoesn't HTTP compression make minification largely unnecessary? It depends. If you have really high traffic or you care about every last microsecond of responsiveness, minification is essential. Also, minifiers these days tend to know about scope and program structure and may even be able to figure out when you're referring to defined browser objects like 'window'. So you just get that much more bang for the buck when combined with other forms of compression. As for your other question, about convention: back in the dark days of the mid-90s Javascript was just the subset of scripts that both IE and Netscape would support. Omitting semicolons usually caused horrible bugs in one or the other. Also, most tools for formatting source code assume that newlines are not significant, and may wrap, split, or join lines in a way that breaks the logic. Anyway, most battles over source code standards end in the most explicit option winning. This case is no exception. Your question is fair, considering that ECMAscript is standardized now. In principle, you could switch to a newline-terminated style, thus saving a whole extra character per line. (But that would be eliminated if you minified). However, even today, I would guess that omitting semicolons risks breakage. Browser makers don't test much with newline-terminated scripts.
- sh1mmer 18y agoMinification has already been mentioned, but I wanted to re-iterate as it's such an important point. You can reduce size over the wire by as much as 30-80% by minifying and obfuscating (something like YUI or Dojo compressors do this). Not having semi-colons risks a lot of code breakage. Doug Crockford's JSMin has an aggressive mode which always strips line breaks and another which doesn't to avoid breakage when semicolons don't exist. Personally I would just say that if you don't use semi-colons you should think hard about why you code at all. I'm not the anal-retentive type but sloppy code isn't awesome. I would put this in the same category as naming variables $whatever or $x. If you've never picked up someones second hand project you may not appreciate why a pleasant coding style matters.
- timknauf 18y agoI wasn't intending to come across as being anti-code-conventions! I love coding and I'm a bit shocked that my questions suggest to you that I might have a sloppy coding style in general. :^) I agree that conventions and shared idioms are extremely important. My question is, "why is this a convention?", not "why should we use conventions at all?". I'm all for adopting the semicolon convention myself, even in sole-programmer projects, if there are reasons for using it; that's basically why I asked the question in the first place. (And of course I adopt it if contributing to a project which already uses it - no need to rock the boat.) Things like minification are exactly what I'm interested in, although I was under the impression that HTTP compression does a better job than Javascript minifiers at solving the size problem. Obfuscation is, of course, another matter entirely.
- adelle 18y agoWelcome to the real world, where "the next programmer to work on this might be dumber than you" is considered a valid justification for cargo-cult programming. A good minifier should replace line-breaks with semicolons as appropriate using all the same inferencing rules as JavaScript itself. Until one of those comes along it seems like using semicolons is necessary to make the best use of the tools that do exist.
- 18y ago
- bdfh42 18y agoExplicit statement termination is all about speed - ensuring that JavaScript interpretation is as rapid as possible. Terminating a statement implicitly requires additional processor cycles - and we still need to husband those cycles to maintain a responsive user experience.
- timknauf 18y agoHmm, interesting point. I've never worked on a truly large JavaScript codebase; it would be interesting to test the effect of implicit and explicit termination on various JavaScript engines. Presumably the performance penalty would apply to traditional interpreter-style engines much more than to modern compiling engines like V8.
- cabalamat 18y agoExplicit statement termination is all about speed - ensuring that JavaScript interpretation is as rapid as possible. Is this correct? I would imagine that JavaScript implementations typically compile it into intermediate code, wihch is then interpreted. If so, then it shouldn't make any difference whether you add the semicolon or not.
- axod 18y agoLeaving out semicolons leads to errors. Ambiguity etc... return [1,2,3] What should that do? Should it return, or return [1,2,3]? There are many other examples. Use semicolons and there is no debate over what should happen. Making them optional in javascript was a ridiculous idea.
- timknauf 18y agoKeep in mind that I come from a mainly Python and Ruby background; both of those languages have always had newline-terminated statements. Yes, neither Python nor Ruby nor newline-terminated Javascript would return the desired result. But neither language seems to be suffering hugely as a result. (As far as I know.) Why would you write a return statement like that in the first place? (Not intended as flamebait - I am genuinely curious to know.) If it is a simple typo that separates the 'return' from the '[1,2,3]', then isn't the negligent typist just as likely to leave off the all-important semicolon? Or is there a genuine reason you might want to put the [1,2,3] on a line by itself?
- axod 18y agook here's a more usual situation in which the programmer is blindly using their favorite bracketing style, and come across the issue... function getObject() { return // returns undefined, not the object. { age: 30, name: "axod" } } Personally I hate that style of bracketing, but some swear by it.
- timknauf 18y agoYeah, not really my favourite bracketing style either. Good example though - it is conceivable that this could happen.
- halo 18y agoJavaScript syntax lets you write statements over multiple lines - if the first line cannot be parsed correctly it assumes you meant to continue over to the second line. This leads to odd error messages and JavaScript being harder to debug without semicolons. Note that this is different to, say, Python, where newline explicitly indicates termination of a statement.
- timknauf 18y agoThanks for the responses, everyone! Sounds like - regardless of what I might think of semicolons personally - the reality of the current crop of minifiers and JavaScript engines makes a case for their continued use. Now, how about ActionScript? This has a compilation step, so the Flash VM is not dealing with your code directly. If we discount ActionScript obfuscators, could a stronger case be made for omitting semicolons there?
- danw 18y agoI highly recommend you use JSlint to pick up on things such as forgotten semi-colons to improve the quality of your code.
- timknauf 18y agoOkay, putting all talk of practicality (interpreters, minifiers, convention) aside, let's look at the language itself for a bit; this could lead to some interesting discussion. JavaScript has two ways of designating the end of a statement. Here is (1): ;\n And here is (2): \n Now, the semicolon can't help you if you type: return\n {a:1\n b:2};\n because statement end (2) has already kicked in, and so the code will return undefined. So, given that statement end (2) is part of the standard (and doesn't look like leaving it anytime soon), is there any language reason to use statement end (1)? Is it purely a visual signifier? If so, is that useful to a majority of coders? Am I in a minority for considering it visual noise? Remember, we're putting aside practicalities like existing conventions, minifier capabilities and browser implementations for the sake of the exercise.