6.3 Finding Elements (Primitives)

Searching elements inside an array depends on whether you are storing primitives or reference types. Primitives are easier, so we start there. Take an array of numbers:

const numbers = [1, 2, 3, 4];

indexOf and lastIndexOf

  • numbers.indexOf(1) — returns 0, the index of the first match, or -1 if the element is not in the array.
  • numbers.indexOf("a") — returns -1; the array does not contain that value.
  • Type matters: numbers.indexOf("1") returns -1 because the array has the number 1, not the string "1".
  • numbers.lastIndexOf(1) — returns the index of the last match, or -1 if absent.
if (numbers.indexOf(1) !== -1) {
  // 1 is present
}

// Cleaner equivalent introduced later in JavaScript:
if (numbers.includes(1)) {
  // 1 is present
}

The pattern indexOf(...) !== -1 is ugly. Modern JavaScript offers Array.prototype.includes(value), which simply returns a boolean. indexOf also accepts a second optional argument, the index at which to start searching: numbers.indexOf(1, 2) begins at index 2.

These methods only work well with primitives — the moment you store objects in an array, equality checks behave differently. We'll see why in the next video about finding reference types.

Summary

This lesson covers three essential JavaScript array search methods—indexOf(), lastIndexOf(), and includes()—designed for locating primitive values within arrays. The session demonstrates how each method works, highlights the importance of type matching in searches, and introduces an optional starting index parameter for refined searches.

Key points

  • indexOf() returns the index position of an element or -1 if not found in the array
  • Type precision matters: searching for the number 1 differs from the string '1'
  • lastIndexOf() locates and returns the last occurrence of an element in an array
  • includes() is a modern method returning a boolean (true/false) for simpler existence checks
  • An optional second parameter in indexOf() and lastIndexOf() specifies where the search begins

FAQ

What is the difference between indexOf() and includes()?

indexOf() returns the index position of the element (or -1 if not found), while includes() returns a boolean indicating whether the element exists. Use indexOf() when you need the position, and includes() for simple existence checks.

Why does type matter when searching for array elements?

JavaScript treats different data types as distinct values. For example, indexOf(1) searching for the number 1 will not match '1' stored as a string, because 1 (number) and '1' (string) are fundamentally different types.

What does the optional second parameter do?

The second parameter specifies the starting index from which the search begins. For instance, indexOf(2, 2) will search for the value 2 starting from index position 2, allowing you to skip earlier occurrences.