What is the difference between includes, indexOf, and find?
Three ways to search an array, returning different things.
includes — returns true/false if a value exists. Simplest existence check.
indexOf — returns the index of a value, or -1 if absent.
find — returns the first element matching a callback (good for objects).
Note: includes detects NaN, but indexOf doesn't. Use find/findIndex to match by a condition.
const nums = [1, 2, NaN, 4, 5];
// includes — boolean
console.log(nums.includes(2)); // true
console.log(nums.includes(NaN)); // true (handles NaN!)
console.log(nums.includes(6)); // false
// indexOf — index or -1
console.log(nums.indexOf(2)); // 1
console.log(nums.indexOf(NaN)); // -1 (cannot find NaN!)
console.log(nums.indexOf(6)); // -1
// find — first matching element
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
const bob = users.find(u => u.name === 'Bob');
console.log(bob); // { id: 2, name: 'Bob' }
// findIndex — index of first match
const bobIndex = users.findIndex(u => u.name === 'Bob');
console.log(bobIndex); // 1includes returns true/false and handles NaN. indexOf returns the position but cannot find NaN (uses ===). find accepts a callback for complex conditions (searching objects by property). findIndex returns the index of the first match (like find but returns index instead of element).
includes for boolean checks, indexOf for position, find for objects/complex conditions. The NaN handling difference (includes finds it, indexOf does not) is the key gotcha. findIndex = find but returns index.