1

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?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
akim
  • 8,255
  • 3
  • 44
  • 60
  • 1
    I don't see any sense to put comment between return and value. – Simone Rossaini Jul 21 '22 at 10:05
  • 1
    it's not the comments that are doing that - try x on a separate line without the comment - this has always been like this in javascript - many have made the mistake of return on a line by itself – Jaromanda X Jul 21 '22 at 10:06
  • `return` keyword at least need 1 argument on the same line. – OMANSAK Jul 21 '22 at 10:10
  • 1
    Sorry, I was unclear: I was not asking for comments on my code, nor fixes. I am asking whether this is the expected behavior. Besides "it's not the comments that are doing that". Well, I beg to differ. Using classical parsing techniques, comments are completely transparent and the source behave as if they were no there. Which is not the case here. – akim Jul 21 '22 at 11:28

1 Answers1

3

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375