

This will be a great scenario if you want to check if a specific value or element exists in a JavaScript array. In fact, undefined is one of the data types similar to Number, Boolean, Null etc. Undefined often seen as bad or error by novice developers but it’s not. If the find() method is unable to find an element that meets the provided condition, it’ll return undefined.Īs you can see, I’m trying to find an age which is above 35Īpparently, none of the elements in the ages array matches that. const users = [Ĭonsole.log(found) // Find() returns Undefined Let’s say you want find the very first object that has an age is over 18, you can do something like the code below. If you’ve array of objects, you can literally find any object by the value of one of its properties. You can make it short like this const ages = Ĭonst found = ages.find(age => age > 18) Ĭonsole.log(found) // 20 Find An Element From Array of Objects You can assign the value that the find() method returns into a variable called found like below. In this case, there is 20 which is 4th index.Īnd exit the loop and it won’t go any further. This will get the very first element of the ages array as soon as it finds any number that is above 18. Let’s say I want to find the first element which is over 18 in the ages array. The parameter age will have an element from an array on each iteration.įinally, add the condition inside the arrow function We need to pass an arrow function as an argument with the parameter called age to the find() method const ages = To capture each element on each iteration Find() Method In Actionįirst, invoke the find() method in the ages javascript array. Including the second element that meets the condition.

Until the condition we specify is met or satisfied. The find() method will search the very first element from a given javascript array It’s one of the higher order functions similar to map, reduce, filter etc.Īny function that accepts or return another function called higher-order functions.Īpparently find() will only take a function as an argument which is required. The find() method can only be invoked on a Javascript array. Find A Specific Array Index Using findIndex().
