Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript find()

find returns the first item that matches a condition.

It is useful for lookups and searches by id.

Why We Need It

Searching lists is common in apps. find makes it simple and efficient.

It stops early, which is faster than filtering everything.

Syntax

array.find((value, index, array) => condition)

Basic Example

1. Find by id

const users = [{ id: 1 }, { id: 2 }];
const user = users.find((u) => u.id === 2);

console.log(user);

Returns the first user with id 2.

Real World Example

2. Not found

const nums = [1, 2, 3];
const result = nums.find((n) => n > 10);

console.log(result); // undefined

If nothing matches, you get undefined.

Multiple Use Cases

First Matching Item

find returns the first element that matches the condition.

If nothing matches, it returns undefined.

Stops Early

find stops searching after the first match.

It is more efficient than filter when you only need one item.

Use Cases

find is great for looking up items by id or key.

Combine with optional chaining for safe access.

More Examples

3. Safe access

const products = [{ sku: "A", price: 10 }];
const item = products.find((p) => p.sku === "B");
const price = item?.price ?? 0;

console.log(price);

Use optional chaining to avoid errors.

4. Find in strings

const names = ["ava", "noah", "liam"];
const result = names.find((n) => n.startsWith("n"));

console.log(result);

find works on any array of values.

Comparison

Without

let found;
for (const u of users) {
  if (u.id === 2) {
    found = u;
    break;
  }
}

With

const found = users.find((u) => u.id === 2);

Common Mistakes and Fixes

Using find for multiple results

Use filter when you need all matches.

Not handling undefined

Check the result or use optional chaining.

Expecting index

Use findIndex if you need the position.

Interview Questions

What does find return when nothing matches?

Undefined.

When is find better than filter?

When you only need the first match.

How do you avoid errors when find returns undefined?

Check the result or use optional chaining.

Practice Problem

Practice: Find the first number greater than 50 in an array.

const nums = [10, 60, 40];
// TODO: find first > 50

One Possible Solution

const nums = [10, 60, 40];
const result = nums.find((n) => n > 50);
console.log(result);

Frequently Asked Questions

What does find return?

The first matching element or undefined.

Does find mutate the array?

No, it does not change the array.

When should I use find?

When you need only the first matching item.

Try It Yourself

Try searching for different ids.