Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to indicate param is optional using inline JSDoc?

People also ask

What is the JSDoc keyword to specify an argument to a function?

The @param tag provides the name, type, and description of a function parameter. The @param tag requires you to specify the name of the parameter you are documenting.

Which function declares an optional parameter?

To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator ('||'): In this approach, the optional parameter is Logically ORed with the default value within the body of the function.

How do you pass optional arguments in JavaScript?

Using the Logical OR operator ('||') In this method, the optional parameter is "Logically ORed" with the default value within the body of the function. In the example below, if the value of b is undefined, 2 is passed instead.

Can you have optional arguments in JavaScript?

Optional parameters are great for simplifying code, and hiding advanced but not-often-used functionality. If majority of the time you are calling a function using the same values for some parameters, you should try making those parameters optional to avoid repetition.


From official documentation:

Optional parameter

An optional parameter named foo.

@param {number} [foo]
// or:
@param {number=} foo

An optional parameter foo with default value 1.

@param {number} [foo=1]

After some digging up I found these are ok as well

/**
 * @param {MyClass|undefined}
 * @param {MyClass=}
 * @param {String} [accessLevel="author"] The user accessLevel is optional.
 * @param {String} [accessLevel] The user accessLevel is optional.
 */

Just slightly more visually appealing than function test(/**String=*/arg) {}


I found a way to do this using Google Closure Compiler type expressions. You put an equals sign after the type like so: function test(/**String=*/arg) {}


In case you are using inline type comments on function arguments and are wondering how to mark a function argument as optional in that notation, I found that just assigning default values to the optional arguments worked. If you want the default to be undefined you have to set it explicitly as well though, otherwise the argument won't be marked as optional (even if it preceded by already optional arguments):

function demo(
  /** @type {String} */ mandatory,
  /** @type {Number} */ optional1 = 0,
  /** @type {Number} optional2 = undefined,
)

If you hover over demo in your IDE you should see both optional1 and optional2 showing up as optional now. In VSCode that is indicated by ? after the argument name (TypeScript notation). If you remove = undefined from optional2 you will see only optional1 being optional which is of course nonsense so the default value here must be explicit like I alluded to in the above paragraph.