Execute Program

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:
    0Pass Icon
  • 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:
    2Pass Icon
  • If we ask for an element that isn't in the array, we get -1.

  • >
    const abc = ['a', 'b', 'c'];
    abc.indexOf('d');
    Result:
    -1Pass Icon
  • It's important to check your .indexOf calls for that -1 return 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 -1 from .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']Pass Icon
  • >
    const abc = ['a', 'b', 'c'];
    abc.slice(abc.indexOf('d'));
    Result:
    ['c']Pass Icon
  • 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 [], or undefined, or null. 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:
    nullPass Icon