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.
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With