views:

196

answers:

3

It is valid JavaScript to write something like this:

function example(x) {
    "Here is a short doc what I do.";
    // code of the function
}

The string actually does nothing. Is there any reason, why one shouldn't comment his/her functions in JavaScript in this way?

Two points I could think of during wiriting the question:

  • The string literal must be initiated, which could be costly in the long run

  • The string literal will not be recognized as removable by JS minifiers

Any other points?

Edit: Why I brought up this topic: I found something like this on John Resig's Blog, where the new ECMA 5 standard uses a not assigned string literal to enable "strict mode". Now it was my interest to just evaluate, if there could be uses or dangers in doing such documentation.

+4  A: 

There's really no point in doing this in Javascript. In Python, the string is made available as the __doc__ member of the function, class, or module. So these docstrings are available for introspection, etc.

If you create strings like this in Javascript, you get no benefit over using a comment, plus you get some disadvantages, like the string always being present.

Ned Batchelder
Some JavaScript engines optimize this and remove the string. `(function(){"foobar"}).toString(-1) === "function () {}"` in Spidermonkey.
Eli Grey
That's cool, but there's still nothing to be gained by doing this in Javascript. Why subvert the design of the language?
Ned Batchelder
I'm not fully sure, if it is subversion: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
Boldewyn
+1  A: 

You're not writing Python, so don't pretend like you are.

Matt Ball
I agree, I just wanted to see, if there are any points in doing this.
Boldewyn
+3  A: 

Instead of giving a point to Matt Ball, I am gonna go ahead and put emphasis by repeating it:

JavaScript is not Python.

leomdg