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 comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.
Square brackets means new Array. var ar=new Array("a","b"); var ar=["a","b"]; //Equal to the syntax above.
A comma is not an option Despite the irrelevance of placing semicolons, it is a whole different story with commas. It is truly important where you put your comma. Defining an array and enumerate elements, you must separate them with a comma.
The brackets around a parameter means that it is optional.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With