Codectionary / Developer documentation / JavaScript

indexOf(), includes(), lastIndexOf()

Use includes() to check whether a value is present, or indexOf() and lastIndexOf() when you need its position. The index methods return -1 when no value matches. None of these methods compares the contents of separate objects: use some() or find() with a property check for that.

Syntax

values.includes(value)
values.includes(value, fromIndex)
values.indexOf(value, fromIndex)
values.lastIndexOf(value, fromIndex)

Examples

Check a saved topic

The first match can be at index 0. Test against -1 instead of treating the index as a boolean.

const saved = ["arrays", "functions", "arrays"];
console.log(saved.includes("arrays")); // true
console.log(saved.indexOf("arrays")); // 0
console.log(saved.lastIndexOf("arrays")); // 2
console.log(saved.indexOf("loops")); // -1
console.log(saved.indexOf("arrays", 1)); // 2

Search objects by the property you need

A new object with the same id is still a different reference. some() answers a property-based yes/no question.

const lesson = { id: "arrays" };
const saved = [lesson];
console.log(saved.includes(lesson)); // true
console.log(saved.includes({ id: "arrays" })); // false
console.log(saved.some(item => item.id === "arrays")); // true

NaN and an empty slot

includes() recognises NaN and reads a missing slot as undefined. indexOf() cannot find NaN and skips missing slots.

const scores = [10, NaN];
console.log(scores.includes(NaN)); // true
console.log(scores.indexOf(NaN)); // -1
const emptySlot = new Array(1);
console.log(emptySlot.includes(undefined)); // true
console.log(emptySlot.indexOf(undefined)); // -1

Parameters and values

  • value: The value to search for. These methods do not convert strings to numbers before comparing.
  • fromIndex (optional): Where to begin, including that position. Defaults to 0 for includes/indexOf and the final index for lastIndexOf. A negative index counts back from the end; it does not change the search direction.
  • Comparison: indexOf and lastIndexOf use strict equality. includes uses SameValueZero, so it can find NaN. All three treat +0 and -0 as equal and compare objects by reference.

Best practices

  • Check an index is not -1 before passing it to splice(); splice(-1, 1) removes the final item.
  • Choose includes() for membership and find() for a condition such as lesson.id === targetId.
  • An empty array returns false from includes() and -1 from either index method.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading