Why use semicolon? [duplicate]
Are there any reasons, apart from subjective visual perception and cases where you have multiple statements on the same line, to use semicolon at the end of statements in JavaScript?
It looks like that there's plenty of evidence suggesting that use of semicolons is highly optional and is required in only few of the specific ca开发者_如何学JAVAses.
Because JavaScript does nasty things to you when it guesses where to put semicolons. It's better to be explicit and let the interpreter know exactly what you meant than it is to let the idiot box guess on your behalf.
References:
- http://www.webmasterworld.com/forum91/521.htm
- http://www.howtocreate.co.uk/tutorials/javascript/semicolons
- http://robertnyman.com/2008/10/16/beware-of-javascript-semicolon-insertion/
...and a cast of thousands.
It looks like there are very few reasons, or, actually, edge cases, when one would want to use semicolons.
http://aresemicolonsnecessaryinjavascript.com/ <- this is down now, use
https://github.com/aresemicolonsnecessaryinjavascript/aresemicolonsnecessaryinjavascript.github.com
If you asked, because you come from a Python background: The difference is:
in Python you shouldn't terminate lines with anything, but are allowed to use the semicolon, if you must
in JavaScript you should terminate the lines with a semicolon, but are allowed (PDF, page 26, point 7.9) to omit it, if it's unambiguous
Because
- Debugging the subtle bugs that occur when you don't is a waste of time you could be spending doing something cool
- It makes it clearer to someone maintaining the code later what you intend
- Not all code maintainers understand the rules for automatic insertion well enough to maintain code with them left out
- Leaving them out relies on all tools that process JavaScript code in your toolchain getting the rules exactly right (for instance, some minifiers/packers/compressors don't, including Crockford's
jsmin
, which will break code that relies on ASI in some places)
As Douglas Crockford suggests -
Put a ; (semicolon) at the end of every simple statement. Note that an assignment statement which is assigning a function literal or object literal is still an assignment statement and must end with a semicolon.
精彩评论