Codectionary / Developer documentation / JavaScript

indexOf(), includes(), lastIndexOf()

These methods search an array for a specific value. indexOf() returns the first matching index (or -1 if not found), lastIndexOf() searches from the end, and includes() simply returns true or false. All use strict equality (===) for comparison, so they cannot find objects by content, only by exact reference.

Syntax

arr.indexOf(value)
arr.includes(value)
arr.lastIndexOf(value)

Examples

indexOf() and includes()

Finding whether and where a value exists in an array.

const fruits = ["apple", "banana", "cherry", "banana"];

console.log(fruits.indexOf("banana"));   // 1 - first match
console.log(fruits.indexOf("grape"));    // -1 - not found
console.log(fruits.includes("cherry"));  // true
console.log(fruits.includes("grape"));   // false

lastIndexOf()

Searching for the last occurrence of a value.

const fruits = ["apple", "banana", "cherry", "banana"];
console.log(fruits.lastIndexOf("banana")); // 3 - the last match

Why includes() Cannot Find Objects by Content

A common gotcha - these methods compare by reference, not deep equality.

const users = [{ name: "Alice" }, { name: "Bob" }];

console.log(users.includes({ name: "Alice" })); // false - different object reference!

// Use .some() with a custom comparison instead
console.log(users.some(u => u.name === "Alice")); // true

Best practices

  • Use includes() when you only need a true/false answer - it is more readable than checking indexOf() !== -1
  • Use indexOf() when you actually need the position of the match, such as for use with splice()
  • Remember these methods use strict equality, so they cannot find objects/arrays by their content - use find() or some() with a custom comparison for that
  • includes() correctly finds NaN (unlike indexOf(), which cannot) - a subtle but useful difference

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation