Does JavaScript Still Work in Commented Out Tags?
As a site designer, you may use JavaScript to make your Web pages more interactive. You might even document your JavaScript by adding informative comments throughout the code. If you place comments around JavaScript tags, the code within the tag will not work. There are, however, benefits to commenting out JavaScript tags.
-
HTML Comments
-
HTML, the language used to create Web pages, consists of tags. A <p> tag, for instance, makes a paragraph appear on a page. Site designers can remove items from a page by deleting a tag or commenting it out as shown in the following example:
<!-- <p>This is a paragraph</p> -->
The greater "<!-- " symbols on the left side of the paragraph tag and the " -->" symbols on the right comment out the tag. The following statement creates a comment that provides documentation:
<!-- We commented out the paragraph because we moved it to a new location -->
This commented statement does not execute in a browser, but it helps developers understand why comments appear around the paragraph tag.
JavaScript Tags
-
A developer adds JavaScript to an HTML document by inserting a <script> tag and a </script> tag into the HTML code. Browsers treat anything between those two tags as JavaScript. You can place these tags in your document's head section, inside the body section or at the end of the document after the closing body tag. Developers also link external JavaScript files by adding a "src" attribute to the tag that points to the file's location on a Web server as shown below:
<script type="text/javascript" src="My_JavaScript_File.js"></script>
-
JavaScript Comments
-
JavaScript consists of statements that may appear inside code blocks called functions. To prevent any statement or function from working, surround it with comments as shown in the following example:
/* var x = 1 */
The "/*" and "*/" characters surrounding the statement comment out the statement. You can also place two forward lashes in front of a single JavaScript statement to prevent it from functioning. The important thing to remember is that either commenting method prevents the commented JavaScript code from doing anything in your application. You can even prevent an external JavaScript file from downloading to a browser by commenting out the <script> tag that references the file.
Tips
-
Comments enable you to try new coding ideas quickly and safely. If you would like to see what would happen if you changed a variable’s value from 100 to 200, you can comment out the original code and replace it with a new statement. Because you don't delete the original code, you can always restore things to normal by deleting the new statement and uncommenting the original. Comments also come in handy when you need to fix a problem quickly. If a critical Web application crashes, for example, you may be able to comment out the <script> tags containing the code that is causing the problem.
-