Searching an array is one of the most common jobs. Pick the method by what you need back.
| Need | Method |
|---|---|
| Is this exact value in the array? | includes() |
| Where is this exact value? | indexOf() |
| The first item that passes a test | find() |
| The position of the first item that passes a test | findIndex() |
| The last item that passes a test | findLast() |
includes and indexOf
They compare with strict equality, which is fine for numbers and strings.
const colors = ["red", "green", "blue"];
console.log(colors.includes("green")); // → true
console.log(colors.indexOf("blue")); // → 2
console.log(colors.indexOf("pink")); // → -1
They do not work for objects (unless it is the very same object), because objects are compared by reference.
const users = [{ id: 1 }, { id: 2 }];
console.log(users.includes({ id: 1 })); // → false
find and findIndex: search with a condition
You pass a function that returns true for the item you want.
const users = [
{ id: 1, name: "Maya", active: true },
{ id: 2, name: "Arjun", active: false },
{ id: 3, name: "Sam", active: true }
];
const arjun = users.find(user => user.id === 2);
console.log(arjun); // → { id: 2, name: Arjun, active: false }
const index = users.findIndex(user => user.name === "Sam");
console.log(index); // → 2
console.log(users.find(user => user.id === 99)); // → undefined
find returns the item or undefined. findIndex returns the position or -1.
findLast and findLastIndex
Same idea, searching from the end (ES2023).
const numbers = [4, 9, 16, 25, 36];
console.log(numbers.findLast(n => n % 2 === 0)); // → 36
Always handle “not found”
const users = [{ id: 1, name: "Maya" }];
const user = users.find(u => u.id === 7);
console.log(user?.name ?? "No such user"); // → No such user
Optional chaining and ?? from the Operators chapter make this tidy.
Both stop early
find stops at the first match. If you only need a yes or no, some() says it more clearly.