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:
-
Create a File:
- Name it
lesson36-find.html
.
- Name it
-
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>
-
-
Save the File.
-
Open it in a Browser to See the First Large Number.
Experiment
- Find the first odd number in an array.
- Get the first product that is out of stock from an inventory list.
- 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.