DEV Community

David Bell
David Bell

Posted on • Originally published at davidbell.space

A Quick Look at the find() Method in JavaScript

(╯°□°) .find()
Enter fullscreen mode Exit fullscreen mode

find() is used to find an element that returns true depending on the condition we have.

const myArr = [1, 4, 6, 9]

const useFind = myArr.find(el => el === 4)
// 4
Enter fullscreen mode Exit fullscreen mode

In the example above we use find() to return the element thats === to 4.

However find() returns the first element it finds.

const myArr = [1, 2, 3, 4, 5, 6]

const useFind = myArr.find(el => el > 2)
// 3
Enter fullscreen mode Exit fullscreen mode

In this example we used a larger array and used find() to return an element > than 2. Even though the array contains more elements greater than 2 it still returned 3. This is because it returns the first element that is true.

Finding Specific Values

find() can be useful when you want a specific id from an array of objects.

const goodBoys = [
  {name: 'spike'},
  {name: 'winston'},
  {name: 'scruffy'}
]
const findDog = goodBoys.find(el => el.name === 'spike')
// { name: 'spike' }
Enter fullscreen mode Exit fullscreen mode

This time we use find() to return us 'spike'.

Let's connect

Twitter

Top comments (0)