Contents
JavaScript indexOf: Main Tips
- This JavaScript
indexOf()
method is used for searching the array for a specified item, then returning its position. - The search starts at your specified position, or at the beginning if no position has been specified.
- The first item has the position of 0, as it usually is in JavaScript array indexes.
indexOf() Function Explained
The JavaScript indexOf()
method is used for searching the array for an item the coder specifies, and returning its position. You can also easily choose at which point of the array should the search begin.
However, if you forget to add the start parameter in the parentheses, the indexOf array JavaScript function will automatically start looking for items from the beginning of the array. Once the array ends, the search concludes as well.
If the searched array does not contain the item, JavaScript indexOf function delivers the return value of -1. In case the item you're searching for is found, the position of its first occurance is returned.
Tip: To perform the search from array's end to start, lastIndexOf() method is used.
See the example provided below. This is how you can search an array for an item x
:
Proper Syntax
Learning the syntax of JavaScript functions should be considered a priority. Take a look at the example below and learn the proper way the indexOf array JavaScript function needs to be included in your code:
array.indexOf(item, start)
We have already established that the JavaScript array find item function can take two arguments in the parentheses. The first one is the parameter called item, and it must be included in the JavaScript indexOf() method. Without it, the function simply won't know what it is supposed to look for in an array. Needless to say, such a search won't produce great results.
The second argument is named start. Unlike item, it is optional: if you want to start the search from the beginning of the array, you may skip defining this argument. However, in cases when you want the search to begin in a certain position in the array, you should set this parameter.
Parameter | Description |
---|---|
item | Required. Defines what the fuction will look for. |
start | Not required. Defines where the search with start. |
Note: if you set start to have a negative value, the search will start at that position counting from the end.
Return Value
Once the JavaScript indexOf()
function is done searching for items in an array, it will present you with results. If the array contained the specified item, the JavaScript array indexOf() method will indicate its location in the array.
However, in cases when the array does not feature the item you searched for, you should expect to receive the return value of -1.
Return Value: | A number which represents the specified item's position. -1 if the item is not found. |
---|---|
JavaScript Version: | ECMAScript 3 |