Piotrek
12/16/2014 9:59:00 PM
In the 6th edition of "JavaScript: The Definitive Guide",
in chapter 2.5 (Optional Semicolons), the following rule
can be found:
"JavaScript treats a line break as a semicolon if the next
nonspace character cannot be interpreted as a continuation of
the current statement".
and the following example is given:
var a
a
=
3
console.log(a)
According to the author, the above shall be treated as:
var a; a = 3; console.log(a);
He justifies it as follows:
"JavaScript does treat the first line break as a semicolon because it cannot parse the code var a a without a semicolon."
but I can't agree with his claim. To start with,
why does he assume these two lines:
var a
a
would be interpreted as:
"var a a" instead of "var aa"?
Where would the extra space between two characters "a" come from?
I'm not saying he's wrong, but the rule says nothing about it.
Let's quote it once again and try to apply to our example,
step by step:
"JavaScript treats a line break as a semicolon if the next
nonspace character cannot be interpreted as a continuation of
the current statement".
What we have in our example is: "var a" followed by a line break,
then a nonspace character ("a") followed by a line break,
another nonspace character ("=") followed by a line break
and one more nonspace character ("3"), the remaining
part is irrelevant.
I see no reason why those three nonspace characters following "var a"
cannot be interpreted as a continuation of it. Which part of
the rule would it violate to concatenate them with the current statement
("var a") to form "var aa=3"? Nothing in the rule seems to force
an implicit semicolon right after "var a".
To make a long story short, why is the discussed example
supposed to be interpreted as:
var a; a = 3; console.log(a);
instead of:
var aa = 3; console.log(a); ?
It looks like either the rule is wrong/incomplete or the example
is wrong. Can you please give the correct rule for optional
semicolons and apply it to my example, step by step?