Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 156 ยท Arrays

Searching Arrays

Search JavaScript arrays the right way. Use includes and indexOf for values, find and findIndex for conditions, findLast, and some and every for yes/no checks.

"Is this item in the list?" "Where is it?" "Give me the first user over 18." "Are all fields filled in?" Searching is one of the most common things you do with arrays, and JavaScript has a method for each kind of question.

The trick is picking the right one. Some methods search for an exact value, others for the first item that matches a condition. Some return the item, some its position, some just true or false. This lesson sorts them into those groups, explains what each returns when nothing is found, and points out the classic traps with NaN, objects and -1.

Quick overview

Question Method Returns when found Returns when not found
Is this value in the array? includes(value) true false
Where is this value? indexOf(value) / lastIndexOf(value) the index -1
Which item matches? find(fn) / findLast(fn) the item undefined
Where is the matching item? findIndex(fn) / findLastIndex(fn) the index -1
Does any item match? some(fn) true false
Do all items match? every(fn) true true for an empty array

All of these stop as soon as they know the answer, and none of them changes the array.

Searching for a value: includes()

includes(value) answers the simplest question: is this exact value in the array?

JS includes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

includes compares with an algorithm called SameValueZero. It's like ===, except that NaN matches NaN. For strings and numbers, that's exactly what you want.

Because it reads so well, ["a", "b", "c"].includes(x) is a common replacement for x === "a" || x === "b" || x === "c".

Finding a value's position: indexOf()

indexOf(value) returns the index of the first match, or -1 if there is none. lastIndexOf(value) searches from the end:

JS indexOf and lastIndexOf

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The -1 result is the biggest trap here. -1 is truthy, and an item at index 0 gives the falsy 0, so if (arr.indexOf(x)) is wrong in both directions. Always compare with -1, or use includes() when you only need a yes or no.

Use indexOf when you actually need the position, for example to remove an item with splice().

Searching objects by value doesn't work

includes and indexOf compare with ===, and objects are compared by reference (see Copying Objects). A new object with the same properties is a different object:

JavaScript
const cart = [{ sku: "A1" }, { sku: "B2" }];

cart.includes({ sku: "A1" }); // false: a different object

To search arrays of objects, you need to describe the match with a function. That's what the next group of methods is for.

Searching with a condition: find() and findIndex()

find(fn) calls your function on each item and returns the first item for which it returns a truthy value. findIndex(fn) returns that item's index instead:

JS find and findIndex

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When nothing matches, find returns undefined, so check before you use the result. Optional chaining (?.) and ?? make that tidy.

find returns the actual object from the array, not a copy. Changing a property on the result changes the item inside the array, which is often exactly what you want and occasionally a nasty surprise.

find vs filter

find returns the first match (or undefined) and stops looking. filter returns all matches in a new array (possibly empty) and always checks every item. If you only need one item, such as a user by ID, find is clearer and faster. Writing users.filter(...)[0] works, but it hides your intent and does extra work.

Searching from the end: findLast() and findLastIndex()

findLast(fn) and findLastIndex(fn) work like find and findIndex, but start at the end of the array. They're perfect for "the most recent" questions when data is stored oldest first:

JS findLast

Press Run (or Ctrl + Enter) to see the console output here.

No output.

findLast and findLastIndex are newer (ES2023). They're supported in all major browsers since 2022 and in Node.js 18+. In older environments, use the reversed-copy approach shown at the end of the example.

Yes/no questions: some() and every()

Sometimes you don't need the item at all, just an answer. some(fn) returns true if at least one item passes the test. every(fn) returns true if all items pass:

JS some and every

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both short-circuit: some stops at the first true, every stops at the first false. That makes them efficient and, as the console shows, a clean way to exit early, which forEach can't do.

The empty-array case surprises people. every on an empty array returns true because there's no item that fails. Mathematicians call this vacuous truth. If "no items" should count as failure in your code, check length first.

some and every are mirror images. "Not every item is valid" is the same as "some item is invalid": !arr.every(isValid) equals arr.some((x) => !isValid(x)). Pick whichever reads more naturally.

Choosing the right method

Ask two questions:

  1. Am I matching an exact primitive value, or a condition? Exact value: includes/indexOf. Condition (or objects): find, findIndex, some, every.
  2. What do I need back? A yes/no: includes, some, every. The item: find/findLast. Its position: indexOf/findIndex. All matches: filter.

For very frequent lookups by a key (like finding users by ID thousands of times), searching an array each time gets slow. A Map or Set answers those questions instantly, and you'll meet both soon.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does ["a", "b"].indexOf("z") return?

    indexOf and findIndex return -1 when nothing matches. Compare with -1 rather than relying on truthiness.
  2. 2. Why is if (list.indexOf(item)) a buggy check?

    A match at index 0 gives 0 (falsy) and a miss gives -1 (truthy). Use includes() or compare with -1.
  3. 3. users.find((u) => u.id === 7) finds no match. What does it return?

    find returns undefined when nothing matches. filter would return an empty array; findIndex would return -1.
  4. 4. Which call returns true for an empty array?

    every returns true when no item fails the test, which is always the case for an empty array.
  5. 5. You need the most recent error in a log stored oldest first. Which is the clearest choice?

    findLast searches from the end and returns the last matching item. find would return the oldest error.

Summary

  • includes(value) answers "is it there?"; it finds NaN and is the cleanest yes/no check for primitives.
  • indexOf/lastIndexOf return a position or -1; always compare with -1.
  • Value searches use ===, so they can't find objects by content; use a callback for that.
  • find/findIndex return the first matching item or its index (undefined or -1 if none); findLast/findLastIndex search from the end.
  • some and every return booleans and stop early; every on an empty array is true.
  • Use find for one match and filter for all matches.

Next: Sorting Arrays โ€” sort with comparators, toSorted and localeCompare.