[Javascript] semicolon insertion paranoia

liorean liorean at gmail.com
Fri May 19 05:47:35 CDT 2006


On 19/05/06, Steve Clay <sclay at ufl.edu> wrote:
> I know that it's poor practice to rely on automatic semicolon insertion at
> the end of lines, but I'm sometimes paranoid that, when I just want to use
> whitespace liberally, some JS engine out there is going to automatically
> insert a semicolon that breaks my statement.

If it doesn't break in the SpiderMonkey or JScript engines, you can
pretty much rely on it to work. SpiderMonkey is in effect the
reference implementation of the language.

> Consider:
>
> function invert(given) {
>   return given
>   ? false
>   : true;
> }

> If "return given" was converted to "return given;", a syntax error would
> occur on the next line, or the function would completely change..

The whitespace handling rules are pretty well defined. The return
statement looks like this:

  "return" [no newlines here] expression

Where the expression is parsed like all other expressions. So, if it
works without being a return statement, it works as a return
statement.

The only case where the semicolon insertion rules can bite you in the
arse in the return statement is if you did place some newline in the
[no newlines here] part.

> Do I need to worry about stuff like this? Would JS engines parse the
> following function /faster/?

No, you needn't worry. And if the speed of parsing is a few
nanoseconds faster or slower, is that important? In my experience,
parsing speed is not a bottleneck. What you should be worried about
when it comes to parsing is whether the parser will code your code the
way you think it will. And in this particular case there's no need to
worry. The semicolon insertion rules are not do-as-you-like, they are
quite well defined.

> function invert(given) {
>   return given ?
>     false
>   : true;
> }

Where you place the '?' is not important. Once the expression parsing
has started, it will follow all rules that happen in all other
expression parsing. Do what makes sense in your coding style.
-- 
David "liorean" Andersson
<uri:http://liorean.web-graphics.com/>



More information about the Javascript mailing list