views:

114

answers:

5

Hello All,

I've seen this tag used after javascript functions for over a decade now and never asked WHY. It's seen in most of the tutorials I've seen over this time, but I usually leave it out... it doesn't seem to have an effect one way or another. Can anyone enlighten me as to why this is used?

If it's just to signify the end of a javascript function, wouldn't the right brace be adequate? If it's for a series of functions, the ending script tag is used.

I doubt I need an example, but for all the other readers out there that are also wondering what it's for, here's some code:



function helloWorld() {
   document.write('Hello World');
}
//-->

Thanks in advance!

+3  A: 

It's to comment out the code, so legacy browsers that don't support JS won't see it.
That's probably pretty much useless nowadays.

Note that it also needs a <!-- in the beginning to make it a comment.

Read this: http://lachy.id.au/log/2005/05/script-comments

NullUserException
*Very* useless, and ugly.
MvanGeest
The tutorials didn't tell me that this is useless and left me wondering for long about how to hide the two slashes at the beginning of a script in non-js browsers as in `//<!-- script... //-->` What would a non-js browser do with it other than showing it to the user and breaking my otherwise wonderful page (with marquees and other cool red text on the yellow background)?
Amarghosh
A: 

If you notice, you can also usually see a <!-- before the scripts.

That syntax is used so browser that don't support Javascript will ignore the body of those scripts.

In fact, in html, anything surrounded by <!-- and --> is considered to be a comment

klez
+6  A: 

It's a holdover from the days when browsers without JS support were reasonably common. If you were including JS code directly in an HTML file, you'd include HTML comment tags (<!-- -->) around the code so those browsers didn't display it as part of the page. The reason for // --> is so that browsers that do support JS didn't try to interpret the closing HTML comment as part of the JS code.

Phil
A: 

It's also useful if you're validating your html code, so the js doesn't appear as invalid html markup. As everyone mentioned however, it's fairly obsolete. I personally try never to have inline javascript, always in an external file that can be cached, which makes this style of coding useless

brad
A: 

Back in the days, some browsers did not handle javascript so to avoid errors, you'd put the javascript code inside an HTML comment block "".

Today, the XHTML standards says you should escape your script like

<script type="text/javascript">
<![CDATA[
... unescaped script content ...
]]>
</script>

You don't have to do that for HTML. Refer to:

http://www.w3.org/TR/xhtml1/
http://www.w3schools.com/tags/tag_script.asp
del.ave