Find array positions with JavaScript indexOf() and lastIndexOf()

indexOf() searches forward for the first matching index, and lastIndexOf() searches backward for the last. Indexes start at zero. Both return -1 when there is no match in the range searched.

Find the first or last position

Run the code in the console to compare the first and last positions of a, 0 and 4. Both methods leave the original array unchanged.

const items = ['a', 'b', 'a', 'c', 'a'];
console.log(items.indexOf('a'));     // 0
console.log(items.lastIndexOf('a')); // 4
console.log(items.indexOf('c'));     // 3
console.log(items.lastIndexOf('x')); // -1

if (items.indexOf(value)) treats index 0 as false and the failure result -1 as true. Compare the return value with !== -1. Use includes() if you only need to know whether the value is present.

Limit the search with fromIndex

The second argument, fromIndex, does not change the direction. Both methods include the starting position. indexOf() moves toward higher indexes and lastIndexOf() toward lower ones. In an array of length 5, -2 becomes index 3.

const items = ['a', 'b', 'a', 'c', 'a'];
console.log(items.indexOf('a', 1));     // 2
console.log(items.lastIndexOf('a', 3)); // 2
console.log(items.indexOf('a', -2));    // 4
console.log(items.lastIndexOf('a', -2)); // 2

console.log(items.indexOf('a', 99));     // -1
console.log(items.lastIndexOf('a', 99));  // 4
console.log(items.indexOf('a', -99));    // 0
console.log(items.lastIndexOf('a', -99)); // -1
console.log(items.lastIndexOf('a', undefined)); // 0

An out-of-range start works differently in each direction. At 99 the forward search has nowhere to look, while the backward search starts at the last index. At -99 the forward search starts at 0 and the backward search has nowhere to look. lastIndexOf('a', undefined) starts at 0, unlike an omitted argument. See ECMAScript: indexOf() and ECMAScript: lastIndexOf().

Understand equality, NaN, and objects

Both methods use strict equality like ===. The number 1 and the string '1' differ. Objects match only when they share the same reference. To match an object’s property, use a predicate such as findIndex(item => item.id === 1).

console.log(['1', 1].indexOf(1)); // 1
console.log([{ id: 1 }].indexOf({ id: 1 })); // -1
console.log([NaN].indexOf(NaN)); // -1
console.log([NaN].includes(NaN)); // true
console.log([NaN].findIndex(Number.isNaN)); // 0

const item = { id: 1 };
console.log([item].indexOf(item));                       // 0
console.log([item].findIndex(entry => entry.id === 1)); // 0
console.log(new Array(1).indexOf(undefined));            // -1
console.log([undefined].indexOf(undefined));             // 0

Check for NaN with includes(NaN) or find its position with findIndex(Number.isNaN). indexOf(undefined) skips holes but matches an element explicitly set to undefined.

Complete example: change the direction and starting point

Save the HTML in UTF-8 as array-index-search.html and open it. For a, the initial results are 0 and 4. Enable the start and enter 3 to get 4 and 2. Entering -2 starts at the same index.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Compare array index searches</title>
</head>
<body>
<label for="value">String to find</label>
<input id="value" type="text" value="a">
<label><input id="use-start" type="checkbox"> Use a starting index</label>
<label for="start">Starting index</label>
<input id="start" type="number" value="2" disabled>
<pre id="output" aria-live="polite"></pre>
<script>
const items = ['a', 'b', 'a', 'c', 'a'];
const value = document.querySelector('#value');
const useStart = document.querySelector('#use-start');
const start = document.querySelector('#start');
const output = document.querySelector('#output');

function show() {
  const term = value.value;
  start.disabled = !useStart.checked;
  const startIndex = start.valueAsNumber;
  if (useStart.checked && !Number.isSafeInteger(startIndex)) {
    output.textContent = "Enter an integer for the starting index.";
    return;
  }
  const first = useStart.checked
    ? items.indexOf(term, startIndex) : items.indexOf(term);
  const last = useStart.checked
    ? items.lastIndexOf(term, startIndex) : items.lastIndexOf(term);
  output.textContent = `Array: ${JSON.stringify(items)}\n` +
    `indexOf(${JSON.stringify(term)}): ${first}\n` +
    `lastIndexOf(${JSON.stringify(term)}): ${last}`;
}

value.addEventListener('input', show);
useStart.addEventListener('change', show);
start.addEventListener('input', show);
show();
</script>
</body>
</html>

Clearing the start field or entering a decimal shows a message. The demo accepts integers for easier comparison. Turn off the starting index to use the method defaults. Enter x to get -1 in both directions.