I was very surprised by the following behavior
f1 = (x) => {
return /* Comment on x. */ x
}
f2 = (x) => {
return /*
Comment on x.
*/ x
}
console.log(f1(1)) // => 1
console.log(f2(2)) // => undefined
This is clearly because f2 is parsed with automatic semicolon insertion as
f2 = (x) => {
return;
x;
};
and indeed, Firefox signals that there's dead code after the return.
Is this really what was meant by Automatic Semicolon Insertion? Is this an implementation issue, or a language issue?
EDIT: someone seems to believe that my question is the same as Why does the value returned should be on the same line as the return statement in JavaScript?. Well, sorry, it is not. I have put a comment that spans over several lines. And in usual parsing techniques, comments behave as if they did not exist, so f2
should be equivalent to
f2 = (x) => {
return x
}
My question is whether this is a defect in the implementation, or whether this handling of comments is conformant to the standard. Why is the multiline comment treated like a linebreak instead of being ignored?
This is expected, it's working as designed. The ES6 specifiction says the following on the grammar for comments:
Comments behave like white space and are discarded except that, if a MultiLineComment contains a line terminator code point, then the entire comment is considered to be a LineTerminator for purposes of parsing by the syntactic grammar.
And this LineTerminator then causes automatic semicolon insertion to kick in, following the usual rules.