Skip to main content

Command Palette

Search for a command to run...

A Quick Look at the find() Method in JavaScript

Updated
2 min read
D

Self taught developer, working with Nextjs, TypeScript, Graphql and React.

(╯°□°)╯ .find()

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

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

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' }

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

Let's connect

Twitter

L

Very helpful and explained well (step-by step). Thank you!!

More from this blog

David Bell

21 posts