The find() method in JavaScript for beginners
Simple and easy step-by-step explanation for beginner coders.
(╯°□°)╯ .find()
The find()
method is useful when you would like to get data considered true
in your condition.
Example 1
Here is an array of numbers. I am looking for the number bigger than 6.
const numbers = [2, 4, 6, 8];
const biggestNum = numbers.find((num) => num > 6);
// 8
Let's do one more.
In this array, I am looking for the number 4. We use the triple equals ===
which means if the element is true to my condition, it will return it.
const numFour = numbers.find((num) => num === 4);
// 4
Example 2
Finding specific values in an array of objects.
In this example is an array of students. We want to find()
the student older than 5.
const students = [
{ name: "Jaxx", age: 5, food: "pizza" },
{ name: "Dami", age: 7, food: "sprouts" },
{ name: "Henry", age: 3, food: "Chicken Nuggets" },
];
const oldestStudent = students.find((student) => student.age > 5);
// { name: "Dami", age: 7, food: "sprouts" }
Let's try one more.
This time, we want to find()
the student with the name "Jaxx".
const studentJaxx = students.find((student) => student.name === "Jaxx");
// { name: "Jaxx", age: 5, food: "pizza" }