简体   繁体   中英

Why does <!— return undefined and not a syntax error?

The html comment tags <!-- & --> return undefined when run as a js command, I expected a syntax error. Why does this happen ?

I stumbled upon this in DoubleClick ... (the download link).

Because <script> was added to HTML as an afterthought, and at the time MANY browsers didn't acknowledge the existence of scripts, <!-- is actually a defined member of the Javascript language spec, and is treated as "start of comment".

Remember that by default, browsers ignore tags that they do not understand, so that

<tag_which_does_not_exist>hi there</tag_which_does_not_exist>

would actually display "hi there" in a browser. For script-unaware browsers, that'd mean they'd actuall display the JS code as text in the document. So..

<script>
<!--
alert('hi there');
// --> 
</script>

would pop up a JS alert in script-aware browsers, and would be completely ignored by script-ignorant browsers.

Also note that --> is NOT valid Javascript, which is why it has to be entered as // --> . // is the other JS single-line comment, and it comments out the otherwise invalid --> html end-of-comment tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM