cf.completefrontendCode editorOpen lab
THE JAVASCRIPT FIELD GUIDE

Searching arrays

Find items and positions by exact value or by a callback condition with indexOf, includes, find, findLast, some, and every.

By the end you can
  • 01
    Pick exact-value methodsUse indexOf, lastIndexOf, and includes without falling for NaN, object-reference, or index 0 bugs.
  • 02
    Search with callbacksUse find, findIndex, findLast, and findLastIndex when the match is a condition.
  • 03
    Ask yes/no questionsChoose some and every, and explain their short-circuit and empty-array behavior.

What searching an array means

Searching an array means asking, “where is the item I care about?” or “does any item have the shape I need?” Arrays are ordered, so JavaScript can scan them from left to right, from right to left, or until a callback says the search is finished.

The curriculum summary for this lesson is short and important: arrays let you find items and positions by value or by condition. A value search is like looking for the exact string "draft". A condition search is like looking for the first product whose price is above 20, even if you do not know that product object ahead of time.

Real-life analogySearching a bookshelf

Imagine a shelf of books. If you know the exact title, you can scan from the left and say, “it is in slot 3,” or “not on the shelf.” If you only care whether it exists, you can answer yes or no. If the question is “show me the first book written after 2010,” you need a test for each book. That is the difference between exact-value methods and callback methods.

In real life: Read titles from left to right
In JavaScript: indexOf scans indexes from 0 upward
In real life: Report the shelf position
In JavaScript: An index such as 2, or -1 for not found
In real life: Ask only “is it there?”
In JavaScript: includes returns true or false
In real life: Ask for the first book after 2010
In JavaScript: find uses a callback test

Where the analogy stops: A bookshelf title search is visual. JavaScript does exact comparisons and callback calls, so two identical-looking object literals are still different objects unless they are the same reference.

This lesson assumes you have met arrays, strict comparisons in the Comparisons lesson, object references in Objects & references, and callbacks in Function expressions & callbacks and Arrow functions. We will keep naming those ideas as they appear.

Which method answers this question?

INTERACTIVE
Array search methods at a glance
MethodReturnsBest forStops early?
indexOf(value)First index, or -1Exact value search with strict equality-style matchingNo callback
lastIndexOf(value)Last index, or -1Exact value search from the rightNo callback
includes(value)BooleanExact membership, including NaNNo callback
find(callback)Item, or undefinedFirst item that passes a testStops at first true
findIndex(callback)Index, or -1Position of first item that passesStops at first true
findLast(callback)Item, or undefinedLast item that passesSearches right to left
findLastIndex(callback)Index, or -1Position of last item that passesSearches right to left
some(callback)BooleanAt least one item passesStops at first true
every(callback)BooleanAll items passStops at first false

Sort the questions by the kind of answer they need. This is the most practical skill: before typing a method name, decide whether you need an exact value, a first match, a last match, or only a boolean.

Which method answers this question?
  • Does roles contain the exact string admin?
  • Give me the first product with price > 100.
  • Where is the first product with price > 100?
  • Show the most recent log entry whose level is error.
  • What position holds the most recent error log?
  • Is any product out of stock?
  • Did every score pass?
  • Where is the exact string draft in statuses?
Try it yourself
0 of 8 correct

Sort by the kind of answer you need. Each card's explanation names a good method.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Where you’ll use this

Array search methods show up anywhere a page holds a list of real data. A shopping cart checks whether an item is already present before adding another row. A settings page finds the first invalid field. A dashboard looks for the latest error. A permissions check asks whether a user has one required role or every required role.

Practical pattern

Start the variable name with the question you are asking: has or is often pairs with some, all with every, first with find, and last with findLast.

These methods do not mutate the array. They inspect it and return an answer. Later lessons cover methods that produce transformed arrays, sort arrays, or copy arrays safely.

Common misconceptions

“indexOf is a safe boolean check.”

No. indexOf returns a number. Index 0 is falsy and -1 is truthy, so if (arr.indexOf(x)) is wrong in both directions. Use includes or compare with !== -1.

“find returns all matches.”

find returns the first matching item. Use filter when you need all matches; that is the headline contrast with the next lesson.

“Object literals with the same properties are equal.”

Arrays compare objects by reference for exact searches. Search for the saved object reference, or use find(obj => obj.id === 1) when you mean “same id.”

“every on an empty array should be false.”

It is true. every looks for a counterexample. An empty array has no item that fails the test.

“findLast is a different kind of callback.”

It uses the same callback idea as find; only the direction changes. It starts at the final index and moves left.

Practice: search arrays on purpose

5 EXERCISES
Exercise 1 · Warm-upPredict the NaN search

Predict both lines before you run the code.

Starter codePop out in the code editor (opens in a new tab)JavaScript
const values = [NaN, "NaN", NaN];
console.log(values.indexOf(NaN));
console.log(values.includes(NaN));

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticeFind the first out-of-stock product

    Which product name prints?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const products = [
      { name: "Tea", inStock: true },
      { name: "Tent", inStock: false },
      { name: "Torch", inStock: true },
    ];
    const match = products.find((product) => !product.inStock);
    console.log(match.name);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeCheck that every score passes

      What boolean does the program print?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const scores = [72, 88, 61];
      console.log(scores.every((score) => score >= 60));

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · ChallengeFind the last error in a log

        Which message prints?

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        const logs = [
          { level: "info", message: "ready" },
          { level: "error", message: "timeout" },
          { level: "error", message: "retry failed" },
        ];
        const latest = logs.findLast((entry) => entry.level === "error");
        console.log(latest.message);

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeFix the indexOf truthiness bug

          The code should print allowed, because admin is present at index 0. Replace the condition with a safe one.

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          const roles = ["admin", "editor"];
          
          if (roles.indexOf("admin")) {
            console.log("allowed");
          }

          Answer, then press Check. Spacing and letter case don’t matter.

            Quiz: check your understanding

            7 QUESTIONS

            Try each answer before reading the explanations. Many wrong answers name a real bug.

            Lesson quiz · 7 questionsScore: first tries count
            1. Question 1 of 7What do indexOf and lastIndexOf print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const letters = ["a", "b", "a"];
              console.log(letters.indexOf("a"));
              console.log(letters.lastIndexOf("a"));

              Choose an answer to see the explanation.

            2. Question 2 of 7Which method should check whether an array contains NaN?

              Choose an answer to see the explanation.

            3. Question 3 of 7What does find print for prices?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const products = [{ price: 10 }, { price: 30 }, { price: 50 }];
              console.log(products.find((product) => product.price > 20).price);

              Choose an answer to see the explanation.

            4. Question 4 of 7Which method returns -1 when no callback match is found?

              Choose an answer to see the explanation.

            5. Question 5 of 7What do findLast and findLastIndex print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const logs = ["error", "warn", "error"];
              console.log(logs.findLast((level) => level === "error"));
              console.log(logs.findLastIndex((level) => level === "error"));

              Choose an answer to see the explanation.

            6. Question 6 of 7What do some and every print for an empty array?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log([].some(Boolean));
              console.log([].every(Boolean));

              Choose an answer to see the explanation.

            7. Question 7 of 7What is the bug in if (items.indexOf("apple"))?

              Choose an answer to see the explanation.

            Key takeaways

            • indexOf and lastIndexOf return indexes or -1; includes returns a boolean.
            • includes(NaN) works, while indexOf(NaN) does not.
            • Objects are compared by reference, so use callback methods when you mean “same property value.”
            • find and findIndex stop at the first callback match; findLast and findLastIndex search from the right.
            • some asks “at least one?” and every asks “all?”; both short-circuit.
            • Never write if (arr.indexOf(x)). Use includes or compare the index to -1.

            Remember the one-liner.
            Array search methods either compare an exact value, run a callback until a match is known, or return a yes/no answer.

            Up next: map, filter & reduce.

            CompleteFrontend Clear concepts. Working examples.