Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commenting JavaScript functions á la Python Docstrings

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.

like image 687
Boldewyn Avatar asked Nov 09 '09 21:11

Boldewyn


People also ask

What are comments and docstrings in Python?

A python comment may be a single line comment or a multiline comment written using single line comments or multiline string constants. Document strings or docstrings are also multiline string constants in python but they have very specific properties unlike python comment.

What's the difference between docstrings and comments?

Comments are great for leaving notes for people working on your program. Docstrings provide documentation about functions, classes, and modules. Use docstrings to teach other developers how to use your program.

Are docstrings like comments?

In programming, a docstring is a string literal specified in source code that is used, like a comment, to document a specific segment of code.

Are there docstrings in Javascript?

But that's where I was wrong — Javascript has docstrings (or its equivalent) and they're the tooltips that I love in VSCode. These guides are wonderful because they articulate the contract that you are agreeing to when you use the method or ask about the property. It's like having MDN right there in your editor.


2 Answers

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.

like image 192
Ned Batchelder Avatar answered Oct 23 '22 10:10

Ned Batchelder


I was looking for a way to add multi-line strings to my code without littering it with \n's. It looks like this module fits the bill: https://github.com/monolithed/doc

Unfortunately, the comments won't survive minification, but I suppose you could write a compile task to convert docstrings to "\n" format.

like image 24
adampasz Avatar answered Oct 23 '22 10:10

adampasz