Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Javascript code inside a non-Javascript browser have extra commenting?

Tags:

javascript

On the W3 tutorial, it shows htis code:

<html>
<body>
<script type="text/javascript">
<!--
document.getElementById("demo").innerHTML=Date();
//-->
</script>
</body>
</html>

Then it says:

The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag.

This doesn't make sense to me. I thought the whole thing got commented out.

like image 663
Caffeinated Avatar asked Apr 27 '26 10:04

Caffeinated


1 Answers

In browsers that do understand JavaScript the opening <-- html comment is ignored and the JS code is executed. The JS comment // on the last line then prevents the closing --> being taken as an error by the JS engine. In browsers that don't understand JavaScript everything between <-- and --> is taken as an html comment and ignored.

This whole thing was a precaution for older browsers that didn't know about JS. It is not necessary for any modern browser.

If you want to comment out a block of JS enclose the block in /* and */.

like image 116
nnnnnn Avatar answered Apr 29 '26 01:04

nnnnnn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!