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?
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?
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).
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
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)