JavaScript Arrays: Index Of
Welcome to the Index Of lesson!
JavaScript arrays' "indexOf" method returns the index of a given value within the array. Be careful: it returns "-1" if the element doesn't exist!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
We can ask an array for the index of a particular value.
>
const abc = ['a', 'b', 'c'];abc.indexOf('a');Result:
0
If the value occurs multiple times, we'll only get the index of the first occurrence.
>
const abc = ['a', 'b', 'c', 'c'];abc.indexOf('c');Result:
2
If we ask for an element that isn't in the array, we get
-1.>
const abc = ['a', 'b', 'c'];abc.indexOf('d');Result:
-1
It's important to check your
.indexOfcalls for that-1return value! Otherwise you can introduce subtle bugs. Here's an example.Let's try to slice an array from a certain element forward. To do that, we'll first grab the element's index with
.indexOf.>
const abc = ['a', 'b', 'c'];abc.slice(abc.indexOf('b'));Result:
This seems to work. But, what if the element we ask for isn't in the array? Then, we'll get back a
-1from.indexOf, and then pass it as an index to.slice.(A hint in case you get stuck:
[1, 2, 3].slice(-1)returns[3].)>
const abc = ['a', 'b', 'c'];abc.slice(abc.indexOf('c'));Result:
['c']
>
const abc = ['a', 'b', 'c'];abc.slice(abc.indexOf('d'));Result:
['c']
That isn't what we intended: there's no
'd'in the array, so we should return some value indicating that fact. For example, we might want to return[], orundefined, ornull. But we definitely don't want to return['c']!We can fix that bug by checking for
-1.>
const abc = ['a', 'b', 'c'];function sliceFromElement(array, element) {const index = array.indexOf(element);if (index === -1) {return null;} else {return array.slice(index);}}sliceFromElement(abc, 'd');Result:
null