JavaScript Comments with Examples
Javascript supports two types of comments (JavaScript Comments). Double-slashes (//) tell javascript to ignore everything to the end of the line. You will see them used most often to describe what is happening on a particular line.
var x=5; // Everything from the // to end of line is ignored(*) var thingamajig=123.45; // 2 times the price of a whatsit.
Block quotes begin a comment block with a slash-asterisk (/*) and Javascript will ignore everything from the start of the comment block until it encounters an asterisk-slash (*/). Block quotes are useful for temporally disabling large areas of code, or describing the purpose of a function, or detailing the purpose and providing credits for the script itself.
function whirlymajig(jabberwocky) { /* Here we take the jabberwocky and insert it in the gire-gimble, taking great care to observe the ipsum lorum! For bor-rath-outgrabe! We really should patent this! */ return (jabberwocky*2); }
You should note that while comments are useful for maintaining the code, they are a liability itself in JavaScript since they will be transmitted along with the code to each and every page load, which can create substantial bandwidth penalties and increase the load time of your page for users.
JavaScript Comments
The result of minimizing your JavaScript is a tiny, compact file which is a fraction of the size of the original which will save you bandwidth and provide speedier page-load time for your
visitors. However the result is also a very un-maintainable source-code mess which is why you should keep a separate, un minimized (and heavily commented) version of the original file. (*) Of special consideration, you should note that the browser itself is ALWAYS looking for a </script> tag to mark the end of your JavaScript and if it finds that tag, intact, in-one-piece, be it in a string or a comment, it is going to stop processing JavaScript at that point and restart processing HTML.
var x=5; /* The browser will break the Javascript when it sees this </script> tag. Everything from tag forward is now being processed as HTML! This is a bad thing! To avoid this you need to avoid using this tag anywhere in your Javascript, and if you must have it, you should break the string out like this... */ document.writeln('</scr'+'ipt>');
This doesn’t mean you shouldn’t comment your code, just that once your code is “finished” you should make a backup copy with the comments, then strip out all the comments in the file which is actually sent to the user.
Also See: JavaScript Output Writeln, alert and getElementById