Should I use semicolons in JavaScript?

Viewed 20929

I've only written a small amount of JavaScript that runs embedded in a Java application, but it was tested using QUnit, has been mixed, and I've not noticed any problems yet.

Is there some conventional wisdom whether to use semicolons or not in JavaScript?

8 Answers

Use them. Use them constantly.

It's far too easy to have something break later on because you neglected a semi-colon and it lost the whitespace which saved it before in a compression/generation/eval parse.

I'd say use them all the time; most code you'll encounter uses them, and consistency is your friend.

They are required by the ECMAscript standard, see section 7.9 - it's just that the standard defines some rules that allow them to be automatically inserted while parsing the script.

So always use them!

I always promote the use of semi-colons when writing JavaScript. Often the interpreter will be able to infer them for you; but I have yet to see a reason (aside from laziness ;-)) why you would deliberately write your code in a less precise fashion than possible.

To my mind, if the structure of the code is obvious, it will be really clear where the semicolons go, such that you won't even have to think about it after getting in the habit (i.e. at the end of each line); on the other hand, if it's not immediately clear to you where the semicolon goes, then chances are the structure isn't the most obvious anyway, and explicit semicolons are needed there more than they would be elsewhere.

It also gets you into the habit of understanding and delimiting statements in your head, so you have a (admittedly marginally) better understanding of how your code might parse into an AST or similar. And that's got to be a good thing when debugging syntax errors.

Use them. There are a few reasons why, most notably

  1. JavaScript minifiers / compressors
  2. Exceptions to the rule that a new line is a new expression (e.g. terminating a line with a variable and starting the next one with a parenthesis, ).)

If you don't use them and then minify your code you can run into issues with all your code being on a single line and the browser doesn't fully grasp which command ends where.

The semicolon triggers auto-indenting in my editor. It is a good enough reason for me to use it always.

And yes, consistency too.

The basic idea of semicolons is to tell the browser that you have just finished a command. You should use them.

Related