2

I was looking at a few things in Javascript. When I got to the call() function I had a look at this on the mozilla js developer page:

Syntax:

fun.call(thisArg[, arg1[, arg2[, ...]]])

I understand what the function does and how it operates but what on earth is that syntax trying to say? Why is there a comma right after that bracket?

[,

Similarly when I was looking up the reduce() function I understand how it works but the syntax shows this:

arr.reduce(callback[, initialValue])

Shouldn't this be something like arr.reduce(callback, initialvalue) instead?

As a noob, the syntax leads me to believe that callback is an array and it has an empty first element and a second element called initialValue. Is there somewhere that I can read about this syntax so that it makes sense, or could some kind person please provide me with some clarity?

EDIT: Also callback refers to a function yes? So why is it callback[] and not callback()?

yoonsi
  • 754
  • 3
  • 10
  • 23

2 Answers2

5

[...] indicates that what is inside is optional. For example, arr.reduce(callback[, initialValue]) can be either arr.reduce(callback) or arr.reduce(callback, initialValue).

The comma is right there meaning that if you will include the second argument, you must put the comma.

Bundit J.
  • 141
  • 1
  • 4
  • Thanks for the response. If you look at the second example I provided there is no [...] however. So how am I supposed to know that one of the arguments is optional? – yoonsi Oct 30 '16 at 07:49
  • Does it imply that the element after the comma (initialValue) is optional and that I must provide the comma if I use this argument? That would make sense. I do wonder though why callback is callback[] and not callback() – yoonsi Oct 30 '16 at 07:51
  • 2
    Just for clarity - it is not a JS syntax, it is just a documentation syntax. – Roman Hocke Oct 30 '16 at 07:51
2

That is a documentation convention and not actual JS syntax.

Square brackets indicate the argument is optional.

The ellipsis indicates that any number of arguments can go there.

fun.call(thisArg[, arg1[, arg2[, ...]]])

means you could say:

 fun.call(foo);
 fun.call(foo, 1);
 fun.call(foo, 1, 2);
 fun.call(foo, 1, 2, 3);
 fun.call(foo, 1, 2, 3, 4);
 fun.call(foo, 1, 2, 3, 4, 5);

etc

arr.reduce(callback[, initialValue])

means you coul dsay:

arr.reduce(foo);

or

arr.reduce(foo, bar);

… but not

arr.reduce(foo, bar, baz);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335