[Javascript] semicolon insertion paranoia
Nick Fitzsimons
nick at nickfitz.co.uk
Fri May 19 05:17:06 CDT 2006
Steve Clay 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.
>
> 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..
>
> Do I need to worry about stuff like this? Would JS engines parse the
> following function /faster/?
>
> function invert(given) {
> return given ?
> false
> : true;
> }
>
> Steve
The rules for automatic semicolon insertion are quite complex and are
defined in section 7.9 of ECMAScript 262 3rd edition, available as a PDF via
<http://www.ecma-international.org/publications/standards/Ecma-262.htm>.
Basically, you don't need to worry, as if one JS engine doesn't choke on
your code, none of them will - or more accurately, one that does is
seriously broken and is thus not worthy of consideration.
As for parsing speed: I don't think it would make any difference. During
parsing, whitespace is just whitespace. Your two examples have the same
number of characters, so there would be no difference because of that;
and as whitespace is just seen as a delimiter, it doesn't matter if it
is made up of spaces, tabs, carriage returns or line feeds - it's just
another character to be skipped over, assuming no semicolon insertion is
required. Internally, once it's been determined that the end of a line
doesn't need semicolon insertion, the parser will just keep looking for
the next token; and as both your cases result in no semicolon insertion,
they will be parsed at the same speed. That aspect of parsing is such a
small proportion of the whole process of downloading, parsing and
executing a script that, even if it could be shown that it did make a
difference, catering to it would definitely be premature optimisation -
making your code harder for you to read and maintain isn't worthwhile
for the sake of a speed increase of a millionth of one percent of the
overall time taken to process the script.
The ECMA 262 standard gives some examples of peculiar conditions that
might cause automatic semicolon insertion when you don't expect it, or
not do so when you _do_ expect it; but if you have a look at them you'll
probably agree that anybody formatting their code the way it has to be
to trigger those cases has bigger problems than semicolons :-)
HTH,
Nick.
--
Nick Fitzsimons
http://www.nickfitz.co.uk/
More information about the Javascript
mailing list