Does it make sense to use HTML comments on blocks of JavaScript?

No, it does not make sense to use HTML comments on blocks of JavaScript in modern web development. HTML comments within JavaScript were a workaround used in the 1990s to hide JavaScript code from very old browsers that didn't understand the <script> tag. Since all modern browsers support JavaScript, this practice is obsolete and not recommended.

Historical Context: Why HTML Comments Were Used

In the early days of JavaScript (1995), browsers like Netscape 1 didn't support the <script> tag. Without HTML comments, these browsers would display JavaScript code as plain text on the webpage. The HTML comment syntax was used to hide the code from these older browsers.

Old Syntax (Not Recommended)

<script type="text/javascript">
<!--
   var message = "Hello World";
   document.write(message);
//-->
</script>

Notice the // before the closing --> to prevent JavaScript from treating it as code.

Why HTML Comments Are No Longer Recommended

There are several reasons why HTML comments should not be used in JavaScript:

  • Obsolete browsers: No modern browser lacks JavaScript support
  • XHTML compatibility: HTML comments can cause issues in XHTML documents
  • Decrement operators: Code with -- operators conflicts with HTML comment syntax
  • Code clarity: Mixing HTML and JavaScript comment syntax is confusing

Example: HTML Comments Still Execute

<html>
<head>
   <title>HTML Comments in JavaScript</title>
</head>
<body>
   <h2>HTML Comments Example</h2>
   <script>
      <!--
         var a = 10;
         var b = 20;
         document.write("Result: " + (a + b));
      //-->
   </script>
</body>
</html>

The code inside HTML comments still executes in modern browsers, making the comments pointless.

Proper JavaScript Comments

Use standard JavaScript comment syntax instead:

<html>
<head>
   <title>Proper JavaScript Comments</title>
</head>
<body>
   <h2>JavaScript Comments Example</h2>
   <script>
      // Single-line comment
      var x = 5;
      
      /*
         Multi-line comment
         This code is properly commented out
         var y = 10;
         document.write(x + y);
      */
      
      document.write("Only x value: " + x);
   </script>
</body>
</html>

Best Practices

Comment Type Syntax Use Case
Single-line // comment Brief explanations
Multi-line /* comment */ Block comments, temporarily disable code
HTML comments <!-- comment --> HTML only, not for JavaScript

For larger JavaScript projects, consider using external JavaScript files and importing them with <script src="filename.js"></script>.

Conclusion

HTML comments in JavaScript are a legacy practice from the 1990s and should be avoided. Use proper JavaScript comment syntax (// and /* */) for better code clarity and modern compatibility.

Updated on: 2026-03-15T23:18:59+05:30

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements