.indexOf()
Anonymous contributor
Anonymous contributor3071 total contributions
Anonymous contributor
Published Jun 21, 2021Updated Jan 18, 2023
Contribute to Docs
The .indexOf()
method returns the first index at which an element can be found. Returns -1
if the element is not found.
Syntax
array.indexOf(element, startIndex);
The following parameters are used in the .indexOf()
method:
- The
element
to be searched for in thearray
. - The optional
startIndex
position to begin searching from. If one is not given, the search starts from the beginning of the array. Negative indices will offset from the end of thearray
.
Examples
In the example below, the index for the number 12
is logged to the console:
const numbers = [6, 12, 8, 10];const indexOf12 = numbers.indexOf(12);console.log(indexOf12);// Output: 1
If element is not found the result will be -1
:
const pizzaToppings = ['pepperoni', 'olives', 'mushrooms'];const indexOfPineapple = pizzaToppings.indexOf('pineapple');console.log(indexOfPineapple);// Output: -1
Check if color 'blue'
is in the colors
array starting with the second element:
const colors = ['blue', 'orange', 'pink', 'yellow', 'teal'];const checkBlue = colors.indexOf('blue', 1);console.log(checkBlue);// Output: -1
Codebyte Example
Multiple matches will only return the first index where a match occurs:
All contributors
- Anonymous contributorAnonymous contributor3071 total contributions
- robgmerrill124 total contributions
- Anonymous contributorAnonymous contributor95 total contributions
- grace_k29 total contributions
- BrandonDusch580 total contributions
- christian.dinh2476 total contributions
- Anonymous contributor
- robgmerrill
- Anonymous contributor
- grace_k
- BrandonDusch
- christian.dinh
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.