0

HTML comments are allowed in Javascript, for older browsers which are not aware of <script> tags.

Ref: Are HTML comments inside script tags a best practice?

So, the JS parser allows <!-- at the start of script, which will be ignored for parsing. And, --> should be prefixed with // so that JS engine ignores them too.

Ref W3C: https://www.w3.org/TR/REC-html40/interact/scripts.html#h-18.3.2

While playing with this, I saw this weird behaviour.

<script>
    <!--
    alert(1);
    -->
</script>

Here, note that --> isn't prefixed by //, which should throw an error by Chrome JS engine. But, Chrome JS engine consider them to be comments, and ignore parsing. Why? (Q1)

And, another behaviour:

<script>
    alert(1);
    -->''>{][}
</script>

This snippet will execute alert. Here, note the place of -->. This specific sequence of characters makes the parser ignore all other incorrect values following it. What I mean is, in place of -->, use any other character/sequence, it will throw error.

So, what's happening here? How --> makes this snippet valid? (Q2)

Note: --> sequence should be prefixed with a new line. That is,

<script>
    <!--
    alert(1); -->''>{][}
</script>

will throw an error. Again, why? (Q3)

unix_root
  • 479
  • 6
  • 18

1 Answers1

-1

Well! All the three code snippets that you have provided gives me error saying "Uncaught SyntaxError: Unexpected token <" on Chrome.

Tavish Aggarwal
  • 820
  • 1
  • 17
  • 41