Geek Geek - 1 month ago 6
Javascript Question

Documentation for optional parameters in JavaScript

From the documentation for

I see the following pattern:

target.addEventListener(type, listener[, useCapture]);


Now I understand that
useCapture
is an optional parameter. Why does the
[
then start before the comma (
,
) and not immediately after the comma that follows the
listener
parameter? What does the enclosing pair of
[]
actually suggest apart from the fact that
useCapture
is optional? I have also seen similar documentation patterns in jQuery documentation, e.g. the
on ()
method documentation
.

.on( events [, selector ] [, data ], handler(eventObject) )

tom tom
Answer

Square brackets mean the thing inside them is optional – either you have it or you don't. It is a concise way of listing the valid invocation forms.

The Basic Example

target.addEventListener(type, listener[, useCapture]);

There are two valid forms:

target.addEventListener(type, listener            ); // without
target.addEventListener(type, listener, useCapture); // with

If the comma was outside the square brackets the two forms would be

target.addEventListener(type, listener,           ); // without (syntax error)
target.addEventListener(type, listener, useCapture); // with

The jQuery Example

.on( events [, selector ] [, data ], handler );

This one is a bit tricky. The selector and data are optional so there are four valid forms:

.on( events                , handler ); // without both
.on( events          , data, handler ); // without selector, with data
.on( events, selector      , handler ); // with selector, without data
.on( events, selector, data, handler ); // with both

The problem is that the second and third forms both have three parameters, so it's not obvious how the arguments will be interpreted. It appears that jQuery decides based on the type of the middle argument: if it's a string the third form is chosen; otherwise the second form is chosen.

So the following will have "hi" as the selector and nothing as the data argument:

.on( events          , "hi", handler ); // "hi" is the selector (!)

To force jQuery to use "hi" as the data argument, null must be given for the selector:

.on( events, null    , "hi", handler ); // "hi" is the data argument

This is unambiguously the fourth form, and the docs say that a null selector is treated the same an omitted selector.

A Nested Example

In documentation you'll often see nested square brackets. Here is a simplified example from the documentation for the Unix command man:

man [--warnings[=type]] page

This means the following forms are valid:

man                   javac    # without outer
man --warnings        javac    # with outer (without inner)
man --warnings=number javac    # with outer (with inner)

But the following would not be valid:

man           =number javac    # is this with or without outer?