469,924 Members | 1,406 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,924 developers. It's quick & easy.

Semi-Colon

I am never sure of when a semi-colon is required in javascript. Is
there a definite rule?

--
Dennis M. Marks
-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----== Over 100,000 Newsgroups - 19 Different Servers! =-----
Jul 20 '05 #1
2 3541
"Dennis M. Marks" <de******@dcsi.net> writes:
I am never sure of when a semi-colon is required in javascript. Is
there a definite rule?


Yes. Not a *simple* rule, but it is definitly there. The appropriate
standard is ECMA 262. The relevant section is 7.9, "Automatic
Semicolon Insertion" (which means that semicolons are required, but
the compiler must insert them if they are missing).

The short summary: A required statement-ending semicolon can be omitted
if
- it is just before a newline (or after, but it is inserted before),
a block-end-bracket, "}", or the end of the program, and
- there is no doubt that a semicolon should be there, i.e.,
removing it doesn't give a syntactically correct program.
That includes cases like
foo();
bar();
(removing the first semicolon would not make it one statement),
and six special cases where a newline isn't allowed:
- between an expression and a following ++ or --,
- between "continue" or "break" and a following identifier, or
- between "return" or "throw" and a following expression.
Cases to avoid are where the program makes sense without the semicolon:
---
function foo(x){return x+42;}

foo; // omit this ; and get another result.
(5)
---

I recommend always using semicolons to end your statements. It is never
wrong, and it is *much* easier to remember.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #2
> I am never sure of when a semi-colon is required in javascript. Is
there a definite rule?


A semi-colon should be placed at the end of every statement. ECMAScript has a
semi-colon insertion rule: In the face of some syntax errors, it will replace a
linefeed with a semi-colon and retry. Professional programmers are troubled by
this.

jslint is a program that will help you to avoid semi-colon errors.

http://www.crockford.com/javascript/lint.html

Jul 20 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Andrey Krivda 232973226 | last post: by
7 posts views Thread by jhomp ssens | last post: by
2 posts views Thread by David Scemama | last post: by
2 posts views Thread by Trond Michelsen | last post: by
2 posts views Thread by James Stroud | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.