5

The syntax for methods such as Array.prototype.indexOf() look like this:

arr.indexOf(searchElement[, fromIndex = 0])

What does [, ...] mean, and why is the comma inside of the brackets?

dbc
  • 104,963
  • 20
  • 228
  • 340
dpren
  • 1,225
  • 12
  • 18
  • 7
    The brackets indicate that any fields inside the brackets are optional. The comma indicates that the properties need to be separated by a comma. You **do not** put those brackets into live code. – Christian Jan 06 '15 at 04:52
  • 3
    This syntax is only for *documentation* and has nothing to do with JavaScript itself. Different documentation systems may choose to encode/display optional arguments and default values differently. – user2864740 Jan 06 '15 at 05:49

3 Answers3

6

The brackets themselves mean "optional", and the = 0 gives the default value should you decide to omit that parameter. The reason why the comma is inside the brackets is because it forms part of the optional bit - if the second parameter is omitted, so is the comma.

In other words, you can use indexOf with only searchElement, in which case fromIndex is assumed to be zero. Or you can specify your own value for fromIndex if you don't want to start searching at element number zero.

So the first two below are equivalent while the third will start searching at a different point in the array:

x = haystack.indexOf (needle);
x = haystack.indexOf (needle, 0);
x = haystack.indexOf (needle, 42);

The Mozilla Developer Network has this to say on the matter (my emphasis):

fromIndex: The index to start the search at.

If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array.

Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched.

Default: 0 (entire array is searched).

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1
arr.indexOf(searchElement[, fromIndex = 0])

Bracket is used to indicate that it's optional to use. And the comma is used to separate the argument.

For eg. you use both then you'd do like this:

arr.indexOf(searchElement, fromIndex)

Or,

//omitting fromIndex use the default to 0
arr.indexOf(searchElement)//As fromIndex is optional to use
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
1

This is to represent multiple function signatures. Those inside [] are optional parameters. So that means either you could invoke it like:

arr.indexOf(searchElement) // in such case fromIndex is 0 by default

or, you could invoke with two arguments:

arr.indexOf(searchElement, fromIndex)
Leo
  • 13,428
  • 5
  • 43
  • 61