9 ms·
Semicolons matter
- musha68k 11y agoFeelings matter
- ArmandGrillet 11y agoNon-ambiguous titles also matter, in this case it should be "Semicolons matter in JavaScript". Too many links have this problem and it makes it difficult to find an article when searching for something on HN.
- ChrisGranger 11y agoAgreed. Even though Hacker News obviously leans towards articles about programming and such, I was half-hoping this was an article about grammar.
- iandanforth 11y agoSome people are grammar geeks; others are code geeks. I'm glad to know we have both.
- rrowland 11y agoGood idea for my next topic. ;) For the record, I didn't post my article here, but if I had I would have specified the language.
- danso 11y agoI know it's not kosher to say "me too" in the comments, but "me too"; I like using semicolons when the previous independent clause doesn't seem substantial enough to be its own complete sentence.
- adrusi 11y agoHonestly when you already have to keep track of JavaScript's other gotchas, having to remember to look for likes that start with ( or [ and precede then with a semicolon is not that much to ask. It seems silly anyway, but not particularly damaging.
- bluedino 11y ago>> Be unambiguous with your code. If you’re ending a statement, use a semicolon. We're still going over this? Javascript, The Good Parts came out close to 10 years ago and went over this.
- soyuka 11y agothey don't matter unless necessary
- 58028641 11y agoI never used semicolons and I have never had a problem. Just avoid ambiguous code.
- Cthulhu_ 11y agoI have a short anecdote where not using semicolons caused problems. Or well, not even in our code. We were using (IIRC) a version of underscore.js that did not use or did not end the final line thing (probably one of them self-executing functions) with a semicolon. Because of reasons, our application would break in production builds; the lack of semicolons would, in some cases, cause an issue after concatenating that file with another vendor's file. A very obscure and hard to track one, too - it took us weeks if not months to find it.
- rhinoceraptor 11y agoThat's why you sometimes see library code wrapped in IIFEs, starting with a semicolon, like so: ;(function () { // Library here }());
- gpvos 11y agoI've seen recommendations to start an included Javascript file with a semicolon to avoid this problem.
- fengb 11y agoJust concat using a semicolon instead of just a new line.
- christophilus 11y agoYeah. I haven't run into these sorts of problems since using a bundler that doesn't just do plain file concatenation (Webpack, Browserify, etc). I think that if you write clear, unambiguous code, and use ES6 modules via Webpack, you can (fairly) safely drop semicolons.
- spinningarrow 11y agoKnowing what you're doing matters.
- amelius 11y agoWhen I click on the link, I get "Error establishing a database connection". Probably a semicolon missing somewhere.
- jack9 11y agoHis example has at least 2 missing semicolons. function Logger() { } // Log something to the console at a specified level Logger.prototype.log = function(level) { console[level || 'log'].apply(console,[].slice.apply(arguments, 1)); }; // here // Sugar functions for Logger.log ['info', 'warn', 'error'].forEach(function(level) { Logger.prototype[level] = function () { return this.log.apply(this, [level].concat(Array.from(arguments))); }; // here });
- deleted 11y ago[deleted]
- draw_down 11y agoAnd yet, not only does it still function as it should without those missing semicolons, the author didn't notice them missing. Hmm. Hmmmmm.
- 0942v8653 11y agoNot sure what you're trying to insinuate, but the first "// here" is the one that broke the code as mentioned in the article.
- nailer 11y agoSo, can someone fill me in why ASI doesn't cover the missing semi for the Logger.prototype.log value? I understand this is the case, I just want to know why. The value is set, it seems like it should end the statement.
- bantunes 11y ago"Error establishing a database connection" - caching matters.
- pbreit 11y agoI don't mind putting them in (not really true) but am still not always certain where they go.
- Cthulhu_ 11y agoYou should install eslint or a similar tool; they have configurable warnings about things like that and will tell you where you should be putting semicolons.
- epmatsw 11y agoSeems like everyone should just be using an automated tool to catch missing/extra semicolons. No reason not to at this point, and eslint even autofixes them for you.
- taylorwc 11y agoThat was my exact reaction too--I wonder how many people who spend any meaningful amount of time in javascript do so without a good linter.
- hyperpape 11y agoOutside of work, I spent a month or two writing little demos for my kids in javascript using notepad. My old computer had died and I was borrowing one. This was in ~2014 maybe?
- kevan 11y agoYep, this is in our ESLint config: "semi": [2, "never"], // Disallow semicolons "no-unexpected-multiline": 2, // Prevent edge cases caused by excluding semicolons. And I haven't thought about it since. I'd expect an article like this 5 years ago, but it feels like bikeshedding at this point. If you choose to not use semicolons then add lint rules to protect against the edge cases and stop wasting brainpower on it.
- degif 11y agoGoogle cache version - http://goo.gl/x6jLVW http://goo.gl/x6jLVW
- deleted 11y ago[deleted]
- deleted 11y ago[deleted]
- draw_down 11y agoMy team doesn't use them (except in a for-loop), hasn't for years, and it's never actually been a problem. Folks need to let this one go, imo.
- musha68k 11y agoI'm with you and I will stoke the fire now that we are in full "productivity" mode: Tabs or spaces? Brains are wired differently plus we "higher" monkeys take our habits seriously serious!
- k__ 11y agoSemicolons cannot save you: https://www.youtube.com/watch?v=Qlr-FGbhKaI https://www.youtube.com/watch?v=Qlr-FGbhKaI Gist: Adding semicolons won't help, because you still have to know how JavaScript inserts them automatically to add them in the right places.
- __david__ 11y agoCorrect me if I'm wrong, but the only case you have to worry about is having "return" on the same line as the thing you want to return. And you have that problem whether or not you use semicolons in the rest of your code.
- k__ 11y agoThe blog post mentions, that starting a line with [ or ( can be dangerous too. But till hat example I didn't even know why this would make sense in the first place. I only use excessive parenthesis for math and store arrays, like the example, in constants that describe their purpose, so I guess I dodged a bullet there :)
- encoderer 11y agoIsn't it as simple as: You only need a semi colon if the next line starts with "[" or "(" ?
- danneu 11y agoYes, at which point the prefixes are easier to notice when they are missing. http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding http://blog.izs.me/post/2353458699/an-open-letter-to-javascr... Either way, no matter your preference, the issue is resolved by having a linter, not by scrutinizing your code for missing semicolons. The OP post feels very dated.
- acdha 11y agoThe idea is that leaving out a semicolon saves an almost imperceptible amount of time but requires you to be deeply familiar with the rules of every JavaScript engine, any minifiers/transpilers/etc. which will ever see that code, etc. and also commits you to rigourously applying that logic to every future change. That's where I'd expect this to come up most frequently – someone writes code, tests it, it works and they move on but later someone makes a change and doesn't notice that the original author left a trap for them. It's easy to avoid that in the “ASI is cool” examples but real programs evolve over time and you never want to make maintenance programming harder.
- encoderer 11y agoIf you're writing idiomatic modern javascript you're using modules -- we no longer have the issue of two JS files being concatenated together in a shared lexical scope. The only rules you need to be familiar with are the 2 I mentioned. In my work, I've never thought about it as "imperceptible" time savings: I worked on a codebase without semi-colons, and then didn't want to go back. It was easier code to work with and write, and the feared downsides never materialized. I still use them to conform with existing code bases or linters that require them, of course, but given the preference..
- acdha 11y ago
- Wintamute 11y agoAre Semicolons Necessary in JavaScript? https://www.youtube.com/watch?v=gsfbh17Ax9I https://www.youtube.com/watch?v=gsfbh17Ax9I
- IshKebab 11y agoKind of insane that this still hasn't been fixed. You should be able to put something like `strict_semicolons;` at the start of a JS file to tell the interpreter to require semicolons for that file.
- Animats 11y agoThe trend towards optional semicolons isn't good. Javascript, Go, and Rust all have different semicolon syntax and semantics.
- __david__ 11y agoSo do Lisp, Haskell, OCaml, Python, and Perl. They're all different languages and should be expected to have grammatical differences. This is not a new trend.
- ansible 11y agoI can't speak for the other two (just learning Rust), but with Go, the auto-insertion of semi-colons has not caused me any problems. It just works.
- nvader 11y agoThe essential difference between Javascript and Go is that in Go, the semicolons are inserted by the lexer[0], while in JS, they're inserted by the parser. I don't know how Rust does it. This means that Go's semicolon insertion rules are really simple: to judge if a statement will end in a semicolon, you only need to examine that line (actually, the last token of that line). In Javascript, on the other hand, the start of the next line needs to be considered as well. If the two lines could possibly be interpreted as one statement together, then they are (except for restricted productions). [ and ( are common offenders that cause lines to "pick up" other lines, but unary + and - can also be candidates when they get promoted to binary operators. [0] https://golang.org/doc/effective_go.html#semicolons https://golang.org/doc/effective_go.html#semicolons
- steveklabnik 11y agoRust doesn't do any special insertion/deletion, but take an expression and add a ; and it becomes a statement.
- aerovistae 11y agoCan someone explain what's happening here? I'm a JavaScript dev, perfectly familiar with JS and with semi-colon insertion, but I'm not following the code after "This is how V8 sees it:" I don't see how or why the two lengthy statements using `apply` are being omitted entirely. I also don't see how that's "perfectly valid code" . . . I tried running it and got an error 'cannot read property forEach of undefined.'
- cornedor 11y agoHe probably left the function empty to keep it simple. And with "perfectly valid code" he's probably referring to not having any syntax error's, which is true.
- DanRosenwasser 11y agoI believe the issue is that the code gets parsed as a function expression that is being indexed by a series of strings in comma expressions. This happens instead of automatic semicolon insertion jumping in and then giving you the "expected" code. As a brief aside, TypeScript could help catch this sort of thing with its `--noImplicitAny` flag turned on.
- thiht 11y agoTo quote the article: "I’ve removed the internals for clarity" The content of the functions is just not relevant to the point he's trying to make
- aerovistae 11y agoOh. I read over that. Thanks.
- proksoup 11y agoI like working on code bases without semi colons better than those with, because the choice to drop is indicative of the team's attitudes, and I often find many other things I like about those softwares. The rules to drop them are simpler than the rules to keep them.
- __david__ 11y ago> The rules to drop them are simpler than the rules to keep them. Hmm. "Semi-colon at the end of each statement" is a pretty easy rule, and I think it'll be hard to top that in simplicity. But I'm open if you've got one.
- proksoup 11y agoHm, there are statements where it's not required, like function definitions[1], so it's more confusing than just "after each statement", no? [1] http://stackoverflow.com/questions/1834642/why-should-i-use-a-semicolon-after-every-function-in-javascript http://stackoverflow.com/questions/1834642/why-should-i-use-...
- deleted 11y ago[deleted]
- msie 11y agoFlame-on: I wish I could blacklist other people's code that don't use semicolons. Perhaps that flagging should be put into a linter. That linter will then update a global list of semicolon-optional code. Flame-off.
- bilalq 11y agoIt still surprises me that this discussion pops up so often. Even more surprising is that people assume as a matter of fact that forgetting to put a semi-colon is the problem. > When your code’s intention is ambiguous, your JavaScript engine will attempt to fill in the gaps. This is kind of misleading. The JS engine isn't making some guess. There are clearly defined semantics on how ASI (automatic semi-colon insertion) operates. Let's put aside whether ASI is good or bad-it's just part of JavaScript. Ending all your lines with semi-colons won't save you, only understanding ASI will do that. Take this example: function foo() { return 'A really long string that I've put on another line'; } console.log(foo()); You'll see that `foo` returned undefined here. Why? Because ASI terminated `return\n` as a statement. Isaac Schlueter wrote a post on this years ago that pretty much says everything I'd want to say on this topic: http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding http://blog.izs.me/post/2353458699/an-open-letter-to-javascr...
- ifdefdebug 11y agoSo if I get you right, return "something"; is parsed as return; "something"; ??? That's just braindead.
- Tloewald 11y agoYes, but unfortunately you can't go back in time and fix it. What we really need is for an analog of "use strict" (e.g. "use strict semicolons" that either (a) eliminates semicolon insertion from Javascript (and just starts throwing errors) or (imho better) (b) eliminates the semicolon altogether (aside from inside for()). Since a huge proportion of production js is being linted using tools that force semicolon insertion, the first option would be pretty painless. Option b — making newline the semantic replacement for ';' would actually be better, since it prevents atrocities like: function wtf(x){ console.log('wtf', x); } /* newline here; strictly correct js */ ("hello world")
- musha68k 11y ago"Semicolons in JavaScript are optional" <3 http://mislav.net/2010/05/semicolons/ http://mislav.net/2010/05/semicolons/
- lacker 11y agoI would prefer finding a subset of JavaScript in which omitting semicolons is okay. Maybe this could be enforced in a linter. For example, if you never begin statements with [ or (, would it be okay to omit all semicolons? A semicolon doesn't seem like much but that's a lot of extra typing over the course of a career.
- mcav 11y agoThis (somewhat insane) linter prohibits unnecessary semicolons: http://standardjs.com http://standardjs.com
- WorldMaker 11y agoThere is a growing number of us moving away from semicolons. I find Typescript useful as the language is (of course) ASI-aware and you can double check that the Typescript compiler's output looks about how you would "expect it". ESLint and TSLint both now have semicolon never options and StandardJS is a simple NPM install standard away towards such an ESLint configuration. Yeah, pretty much the only "rules" are to know never to add a line break after keywords such as return (which is the same rule as languages such as Python and which is also something you have to know, regardless of semicolons) and the "Winky Frown Rule": (, [, and ` all have to be winky frowns if you start a line with one: ;(, ;[, ;` It's pretty liberating writing JS/ES/TS without semicolons, and with ES2015 syntax things, makes the language feel like Python or an OCaML relative (which it sort of is).
- swang 11y agoI will write the function, While you go have a beer Where is my module support? Where is my linter library? Where is my code ending? Where have all the semicolons gone? --- Sing to Paula Cole's "Where have all the Cowboys Gone?"
- z3t4 11y agoWhether you are writing semicolons or not. Don't start a new line with (, [, /, +, ++, or --. And never have a line break after return, break or continue.
- gregmac 11y agoObligatory: https://pbs.twimg.com/media/B5LU4F7CUAELcIU.png https://pbs.twimg.com/media/B5LU4F7CUAELcIU.png
- erikpukinskis 11y agoMeh. I don't use semicolons at all in JavaScript, except in for loops. I've never once had a bug from it. I'll stick to caring about he myriad issues that actually cause quality problems for me rather than worry about obscure theoretical bugs.
- iLemming 11y agoOMG. Reasonable people already learned that Clojurescript, Elm and Purescript are much, much, much better, so why are you still debating about semicolons?
- alexandrerond 11y agoWhy is this discussion always attached to JavaScript and not to Ruby or Go?