JavaScriptIntermediate

JavaScript find, findIndex, some, every and includes

Learn to search and test arrays in JavaScript: find items and positions with find and findIndex, check conditions with some and every, and use includes.

All JavaScript lessons

What you will learn

Very often you do not want to transform a whole list. You just want to ask it a question:

  • “Which user has the id 7?”
  • “Is there any product that is out of stock?”
  • “Did every student pass?”
  • “Where is this item in the list?”

JavaScript has a method for each question: find, findIndex, some, every and includes. In this lesson you will learn what each one returns, how they differ from filter, and how to use them in real code like login checks, form validation and cart updates.

The big picture

Method Question Returns
find(fn) Which is the first item that matches? The item, or undefined
findIndex(fn) Where is the first match? The index, or -1
some(fn) Does at least one item match? true / false
every(fn) Do all items match? true / false
includes(value) Is this exact value in the list? true / false

All of them stop as soon as they know the answer (this is called short-circuiting), so they can be faster than filter. None of them changes the original array.

The sample data used in this lesson:

const users = [
  { id: 1, name: "Riya", age: 20, active: true },
  { id: 2, name: "Karan", age: 17, active: true },
  { id: 3, name: "Neha", age: 25, active: false }
];

find: get the first matching item

find goes through the array and returns the first item for which your callback returns a truthy value. If nothing matches, it returns undefined.

const numbers = [5, 12, 8, 130, 44];

const firstBig = numbers.find((n) => n > 10);
console.log(firstBig);   // 12  (not 130, because 12 comes first)

const none = numbers.find((n) => n > 1000);
console.log(none);       // undefined

With objects, it is the best way to look something up:

const users = [
  { id: 1, name: "Riya" },
  { id: 2, name: "Karan" },
  { id: 3, name: "Neha" }
];

const user = users.find((u) => u.id === 2);
console.log(user);        // { id: 2, name: "Karan" }
console.log(user.name);   // "Karan"

Always check for undefined

If nothing matches, find returns undefined, and reading a property of undefined crashes your program:

const users = [
  { id: 1, name: "Riya", age: 20, active: true },
  { id: 2, name: "Karan", age: 17, active: true },
  { id: 3, name: "Neha", age: 25, active: false }
];

const missing = users.find((u) => u.id === 99);

console.log(missing.name);   // TypeError: Cannot read properties of undefined

Check first:

const users = [
  { id: 1, name: "Riya", age: 20, active: true },
  { id: 2, name: "Karan", age: 17, active: true },
  { id: 3, name: "Neha", age: 25, active: false }
];

const missing = users.find((u) => u.id === 99);

if (missing) {
  console.log(missing.name);
} else {
  console.log("User not found");
}

find gives you the real object

find does not copy anything. It returns a reference to the same object that is inside the array. If you change it, the array changes too:

const users = [
  { id: 1, name: "Riya", age: 20, active: true },
  { id: 2, name: "Karan", age: 17, active: true },
  { id: 3, name: "Neha", age: 25, active: false }
];

const riya = users.find((u) => u.name === "Riya");
riya.name = "Riya Sharma";

console.log(users[0].name);   // "Riya Sharma"

findIndex: get the position

findIndex works like find, but returns the index instead of the item. If nothing matches, it returns -1.

const users = [
  { id: 1, name: "Riya" },
  { id: 2, name: "Karan" },
  { id: 3, name: "Neha" }
];

console.log(users.findIndex((u) => u.name === "Neha"));   // 2
console.log(users.findIndex((u) => u.name === "Zara"));   // -1

You need the index when you want to change the array itself, for example with splice:

const users = [
  { id: 1, name: "Riya", age: 20, active: true },
  { id: 2, name: "Karan", age: 17, active: true },
  { id: 3, name: "Neha", age: 25, active: false }
];

const index = users.findIndex((u) => u.id === 2);

if (index !== -1) {
  users.splice(index, 1);   // remove Karan
}

console.log(users.map((u) => u.name));   // ["Riya", "Neha"]

Remember: a missing item gives -1, and index 0 is falsy. Never write if (findIndex(...)). Compare with -1.

indexOf vs findIndex

  • indexOf(value) looks for an exact value (good for numbers and text).
  • findIndex(fn) looks for the first item that passes a test (good for objects).
const users = [{ name: "Riya" }, { name: "Karan" }];

console.log(["a", "b", "c"].indexOf("b"));                  // 1
console.log(users.findIndex((u) => u.name === "Karan"));    // 1

findLast and findLastIndex

Newer JavaScript also has findLast() and findLastIndex(), which search from the end. They are handy for “the most recent item that matches”:

const scores = [40, 75, 90, 55, 80];

console.log(scores.findLast((s) => s > 70));        // 80
console.log(scores.findLastIndex((s) => s > 70));   // 4

some: is there at least one?

some returns true if any item passes the test. It stops at the first true.

const ages = [22, 17, 30];

console.log(ages.some((age) => age < 18));    // true  (17 matches)
console.log(ages.some((age) => age > 100));   // false

Think of it as OR: “first OR second OR third…”.

const users = [
  { id: 1, name: "Riya", age: 20, active: true },
  { id: 2, name: "Karan", age: 17, active: true },
  { id: 3, name: "Neha", age: 25, active: false }
];

const hasInactiveUser = users.some((u) => !u.active);
console.log(hasInactiveUser);   // true

every: do all items pass?

every returns true only if every item passes the test. It stops at the first item that fails.

const marks = [72, 85, 90, 64];

console.log(marks.every((m) => m >= 40));   // true  (everyone passed)
console.log(marks.every((m) => m >= 70));   // false (64 fails)

Think of it as AND: “first AND second AND third…”.

some and every are opposites

const numbers = [2, 4, 6, 7];

console.log(numbers.every((n) => n % 2 === 0));   // false (7 is odd)
console.log(numbers.some((n) => n % 2 !== 0));    // true  (7 is odd)

“Not every item is even” means the same as “some item is not even”.

The empty array surprise

On an empty array, the two methods give answers that look odd but are logical:

console.log([].some((n) => n > 5));    // false (no item can match)
console.log([].every((n) => n > 5));   // true  (no item breaks the rule)

every is true for an empty list because nothing fails. Remember this when you validate lists, for example “all fields are filled” is true if there are no fields at all.

includes: is this value in the list?

includes checks whether an exact value exists. It returns true or false.

const fruits = ["apple", "banana", "mango"];

console.log(fruits.includes("banana"));   // true
console.log(fruits.includes("Banana"));   // false (case matters)
console.log([1, 2, 3].includes(2));       // true
console.log([1, 2, 3].includes("2"));     // false (strict comparison)

includes does not work for objects

const users = [{ name: "Riya" }];

console.log(users.includes({ name: "Riya" }));            // false (a different object)
console.log(users.some((u) => u.name === "Riya"));        // true  (use some)

Objects are compared by identity, not by content. To test objects, use some with a condition.

includes with a start position

console.log([1, 2, 3, 1].includes(1, 1));   // true  (search from index 1: finds the last 1)

You will rarely need this.

Which method should I use?

I want to… Use
Get the item that matches find
Get the position of a match findIndex
Know if any item matches some
Know if all items match every
Check if a simple value is in the list includes
Get all matching items filter

find or filter?

const users = [
  { id: 1, name: "Riya", age: 20, active: true },
  { id: 2, name: "Karan", age: 17, active: true },
  { id: 3, name: "Neha", age: 25, active: false }
];

// filter: always returns an array (maybe empty), and checks every item
const matches = users.filter((u) => u.id === 2);   // [{...}]

// find: returns the item itself, and stops at the first match
const match = users.find((u) => u.id === 2);       // {...}

When you expect only one result (like an item with a unique id), find is cleaner and faster.

some or filter(...).length > 0?

Both work, but some stops at the first match and says what you mean:

const users = [
  { id: 1, name: "Riya", age: 20, active: true },
  { id: 2, name: "Karan", age: 17, active: true },
  { id: 3, name: "Neha", age: 25, active: false }
];

const hasAdult = users.some((u) => u.age >= 18);                  // better
const hasAdultOld = users.filter((u) => u.age >= 18).length > 0;  // works, but wasteful

Real-life use cases

1. Look up a product by id

const products = [
  { id: 101, name: "Notebook", price: 80 },
  { id: 102, name: "Headphones", price: 1500 },
  { id: 103, name: "Pen", price: 20 }
];

function getProduct(id) {
  return products.find((p) => p.id === id);
}

const product = getProduct(102);

if (product) {
  console.log(`${product.name}: ₹${product.price}`);   // "Headphones: ₹1500"
} else {
  console.log("Product not found");
}

2. Login check

const accounts = [
  { email: "riya@example.com", password: "abc123" },
  { email: "karan@example.com", password: "xyz789" }
];

function login(email, password) {
  const account = accounts.find(
    (a) => a.email === email && a.password === password
  );

  return account ? "Welcome back!" : "Wrong email or password";
}

console.log(login("riya@example.com", "abc123"));   // "Welcome back!"
console.log(login("riya@example.com", "nope"));     // "Wrong email or password"

(Real websites never store plain passwords like this. It only shows how find works.)

3. Form validation with every

const fields = [
  { name: "username", value: "riya" },
  { name: "email", value: "riya@example.com" },
  { name: "password", value: "" }
];

const allFilled = fields.every((f) => f.value.trim() !== "");
console.log(allFilled);   // false

const emptyFields = fields.filter((f) => f.value.trim() === "").map((f) => f.name);
console.log(emptyFields);   // ["password"]

Use every to decide whether the form is valid, and filter to find which fields are wrong.

4. Permission check with some and includes

const userRoles = ["editor", "viewer"];
const allowedRoles = ["admin", "editor"];

const canEdit = userRoles.some((role) => allowedRoles.includes(role));
console.log(canEdit);   // true

5. Is everything in stock?

const cart = [
  { name: "Notebook", stock: 5 },
  { name: "Pen", stock: 0 }
];

const canCheckout = cart.every((item) => item.stock > 0);
const outOfStock = cart.find((item) => item.stock === 0);

console.log(canCheckout);          // false
console.log(outOfStock.name);      // "Pen"

6. Add to cart, or increase the quantity

const cart = [{ id: 1, name: "Notebook", qty: 1 }];

function addToCart(id, name) {
  const existing = cart.find((item) => item.id === id);

  if (existing) {
    existing.qty++;                        // already there: increase
  } else {
    cart.push({ id: id, name: name, qty: 1 });   // new item
  }
}

addToCart(1, "Notebook");
addToCart(2, "Pen");

console.log(cart);
// [{ id: 1, name: "Notebook", qty: 2 }, { id: 2, name: "Pen", qty: 1 }]

7. Remove an item by id

const todos = [
  { id: 1, task: "Buy milk" },
  { id: 2, task: "Study JS" },
  { id: 3, task: "Walk" }
];

const index = todos.findIndex((t) => t.id === 2);

if (index !== -1) {
  todos.splice(index, 1);
}

console.log(todos.map((t) => t.task));   // ["Buy milk", "Walk"]

8. Find the first free seat

const seats = [
  { number: 1, booked: true },
  { number: 2, booked: true },
  { number: 3, booked: false },
  { number: 4, booked: false }
];

const free = seats.find((seat) => !seat.booked);
console.log(free ? `Seat ${free.number} is free` : "Fully booked");   // "Seat 3 is free"

9. Password rules

const password = "hello123";

const rules = [
  (p) => p.length >= 8,
  (p) => /\d/.test(p),
  (p) => !p.includes(" ")
];

const isStrong = rules.every((rule) => rule(password));
console.log(isStrong);   // true

The rules are functions, and every runs each rule on the password. (/\d/.test(p) checks for a digit. Regular expressions have their own lesson.)

Common mistakes

  • Using the result of find without checking. It may be undefined, and undefined.name crashes.
  • Using if (array.findIndex(...)). Index 0 is falsy and -1 is truthy. Compare with -1.
  • Using includes for objects. Use some with a condition.
  • Using filter(...)[0] when you want one item. find is shorter and faster.
  • Using filter().length > 0 to check existence. Use some.
  • Forgetting that every is true on an empty array. Check array.length if that matters.
  • Forgetting the case of text. includes("apple") will not find "Apple". Compare lower-case versions.
  • Assuming find returns a copy. Changing it changes the original object in the array.
  • Forgetting return in the callback when you use braces. find((u) => { u.id === 2 }) always gives undefined.
  • Mixing up some (OR) and every (AND).
  • Thinking find returns all matches. It stops at the first one. Use filter for all of them.

Practice

  1. Given [3, 8, 12, 5, 20], use find to get the first number greater than 10, and findIndex to get its position.

  2. Given an array of 4 users with id and name, write getUserName(id) that returns the name, or "Unknown" if there is no such user.

  3. Check whether any number in [1, 3, 5, 8] is even, using some.

  4. Check whether all words in ["apple", "banana", "mango"] have more than 4 letters, using every.

  5. Write isInList(list, value) that returns true or false using includes. Test it with "Apple" and "apple".

  6. Given a list of products with inStock, write allAvailable(products) using every, and getOutOfStock(products) using filter.

  7. Predict the output, then run it:

    console.log([].every((x) => x > 0));
    console.log([].some((x) => x > 0));
  8. Write toggleDone(todos, id) that finds the todo with that id and flips its done value. Handle the case where the id does not exist.

  9. Write a function removeById(list, id) that returns a new array without the item (use filter), and another version that changes the original (use findIndex and splice).

  10. Challenge: you have an array of students, each with name and an array of marks. Print the names of students for whom every mark is at least 40.

Recap

  • find(fn) returns the first matching item, or undefined. Always check before using it.
  • findIndex(fn) returns the index of the first match, or -1. (findLast and findLastIndex search from the end.)
  • some(fn) is true if at least one item passes (OR). every(fn) is true if all items pass (AND).
  • every returns true for an empty array, and some returns false.
  • includes(value) checks for an exact value (strict, case-sensitive). It does not work for objects, so use some.
  • All of them stop early and do not change the original array.
  • Use find instead of filter()[0], and some instead of filter().length > 0.
  • find returns the real object inside the array, not a copy.
  • Next you will learn sorting and flattening: sort, custom sorting, reverse, flat and flatMap.