Searching Arrays with indexOf and lastIndexOf

In JavaScript, the indexOf() method returns the first index at which a specified element can be found in an array. If it does not exist in the array, -1 is returned instead. Similarly, lastIndexOf() returns the last index where an element appears or -1 if it doesn't exist within the array. These methods are incredibly useful when searching for elements and are commonly used in various coding instances.

Syntax

lastIndexOf(searchElement)
lastIndexOf(searchElement, fromIndex)


Parameters

searchElement

Element to locate in the array.

fromIndex Optional

Zero-based index at which to start searching backwards, converted to an integer.

  • Negative index counts back from the end of the array - if fromIndex < 0, fromIndex + array.length is used.
  • If fromIndex < -array.length, the array is not searched and -1 is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so searchElement is never found.
  • If fromIndex >= array.length or fromIndex is omitted, array.length - 1 is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements.


Return value

The last index of the element in the array; -1 if not found.