Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
A X
12,842 PointsUse of Semicolons in JavaScript
I'm learning a few languages here at Treehouse, and I've noticed most of the other languages use semicolons (;) only to signify the end of a statement. Javascript seems to use it, if I'm understanding correctly, after every command, like document.write, alert, prompt, and if/else. Why is JavaScript different? Am I correct in my understanding of the use of semicolons? Thanks!
3 Answers
miikis
44,957 PointsThis StackOverflow thread — particularly this answer — should clear it up a little bit.
Essentially, it's a matter of preference and usability. JS has Automatic-Semicolon Insertion(AST) that makes it so that you technically don't have to include semicolons. I've found that not including semicolons is more practical if you're working with JS on the server (NodeJS). With client-side JS — JS in the browser — you'll often want to minify and concatenate your code — for performance reasons — and not including semicolons can lead to some painful and obscure ambiguities.
Jennifer Nordell
Treehouse TeacherJavaScript is a bit different in that it's an interpreted language. The parser will try to insert a semicolon for you after a statement if you've omitted it. But best practice is to use a semicolon after every complete statement to avoid confusion (both for yourself and the interpreter). I found an archived document on semicolon insertion here: http://www-archive.mozilla.org/js/language/js20-2000-07/rationale/syntax.html
Keep in mind that a "command" like document.write/alert/prompt are statements :)
Matthew Hendricks
4,168 PointsSemi-colons are used at the end of the statement (or at least they should be). What may be different in JavaScript from what you have seen in other languages is there are some rules in the JS spec which will automatically insert semi-colons while your JS is being parsed. To be honest, I'm not 100% clear on when they can be omitted, but understand the rules revolve around the end of the file, end of braces, and when given a new line. This is a pretty good read on when they may be omitted: http://inimino.org/~inimino/blog/javascript_semicolons