Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 36 - JavaScript Array Method – find()

The find() method is used to search for the first element in an array that satisfies a given condition. If no element matches, it returns undefined.

Explanation

  • It loops through the array and applies a callback function to each element.
  • If an element meets the condition, it is returned immediately.
  • If no element matches, it returns undefined.

Syntax

let foundElement = array.find((element, index, array) => {
    return condition;
});
  • element: The current item being processed.
  • index (optional): The index of the current element.
  • array (optional): The array being searched.

Example 1: Finding the First Even Number

let numbers = [3, 7, 10, 15, 20];

let firstEven = numbers.find(num => num % 2 === 0);

console.log(firstEven); // Output: 10
  • Returns the first even number (10), not all even numbers.

Example 2: Finding a Specific Object in an Array

let users = [
    { name: "Alice", age: 25 },
    { name: "Bob", age: 30 },
    { name: "Charlie", age: 35 }
];

let user = users.find(person => person.age > 30);

console.log(user); // Output: { name: "Charlie", age: 35 }
  • Returns the first person with an age greater than 30.

Example 3: Searching for a Missing Value

let numbers = [2, 4, 6, 8];

let found = numbers.find(num => num > 10);

console.log(found); // Output: undefined
  • Returns undefined since no number is greater than 10.

Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson36-find.html.
  2. Write the Code:

    • Copy the following:

      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Lesson 36 - find() Method</title>
      </head>
      <body>
      <h2>First Number Greater than 50</h2>
      <p id="result"></p>
      
      <script>
         let numbers = [10, 20, 30, 40, 60, 80];
      
         let firstLarge = numbers.find(num => num > 50);
      
         document.getElementById("result").textContent = "First number > 50: " + firstLarge;
      </script>
      </body>
      </html>
  3. Save the File.

  4. Open it in a Browser to See the First Large Number.

Experiment

  1. Find the first odd number in an array.
  2. Get the first product that is out of stock from an inventory list.
  3. Find the first word in a list that starts with "J".

Key Takeaways

  • find() returns the first element that matches the condition.
  • If no match is found, it returns undefined.
  • Useful for searching and retrieving a single object or value.