4

Consider the following three lines of Javascript.

console.log(1); --> console.log(2); console.log(3);

I would expect it to cause a Syntax Error, probably something like Unexpected token --.

Instead, browsers seem to accept the code, and simply ignore the second line, producing the output:

› 1 › 3 

I've tried pasting the snippet into the consoles of Chrome, Safari and Firefox. All of them behave the same way. What's going on?

4
  • @Pointy Which context specifically? Works everywhere I've tried, including Node.js Commented Jan 23, 2019 at 14:56
  • It does behave the same in Node.js (v8.9.4) when I run it from a .js file (node index.js) Commented Jan 23, 2019 at 15:00
  • 1
    Well it was failing for me (10.15.0) but in any case you found the (surprising, to me) rule in the grammar. I'm sure it's there for ancient code, though it seems like an extremely nasty oddity that could really ruin one's day :) Commented Jan 23, 2019 at 15:04
  • Deleted my incorrect comments. Commented Jan 23, 2019 at 15:05

3 Answers 3

3

It is part of a HTML comment for older browser with the pattern to have Javascript parts in browsers who do not support the <script> tag.

<script> <!-- // some code --> </script> 
Sign up to request clarification or add additional context in comments.

Comments

2

Apparently ECMAScript officially allows "HTML like" comments:

B.1.3 HTML-like Comments

The syntax and semantics of 11.4 is extended as follows except that this extension is not allowed when parsing source code using the goal symbol Module:

HTMLCloseComment:: WhiteSpaceSequence opt SingleLineDelimitedCommentSequence opt --> SingleLineCommentChars opt 

Which suggests that whatever comes after --> should be treated as a comment.

1 Comment

Ah and it fails in Node because of that caveat at the top of that section. Good find!
1

Messing around with the console seems to prove Nina's case

--> undefined typeof --> Uncaught SyntaxError: Unexpected token > --> = "foo" undefined --> undefined --< Uncaught SyntaxError: Unexpected token < <-- Uncaught SyntaxError: Unexpected token < <!-- undefined <!-- foo --> undefined 

It seems that these keywords are set to always return undefined.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.