Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: comma after opening bracket of parameter in syntax example

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?

like image 223
dpren Avatar asked Jan 06 '15 04:01

dpren


People also ask

How do you write commas in JavaScript?

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.

What do brackets around a variable mean in JavaScript?

Square brackets means new Array. var ar=new Array("a","b"); var ar=["a","b"]; //Equal to the syntax above.

Are commas necessary in JavaScript?

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.

What do brackets mean in documentation?

The brackets around a parameter means that it is optional.


1 Answers

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

like image 123
paxdiablo Avatar answered Oct 29 '22 18:10

paxdiablo