find and includes
When you want one item rather than a list, find gives you the first match, and includes just tells you whether something is there.
find returns the first matching item or undefined; findIndex returns its position or -1. includes and indexOf work on plain values. Choosing find over filter makes the intent clear and stops at the first hit.
EXERCISE
1find: The First One That Matches
find runs the same kind of test as filter but hands back a single item instead of an array, and stops as soon as it succeeds.
The shape:
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Grace" },
{ id: 3, name: "Alan" },
];
const user = users.find((u) => u.id === 2);
console.log(user); // { id: 2, name: 'Grace' }
console.log(user.name); // Grace
Nothing matching gives undefined, not an empty array:
const missing = users.find((u) => u.id === 99);
console.log(missing); // undefined
// console.log(missing.name); TypeError: Cannot read properties of undefined
// So a find result usually needs checking:
if (missing) {
console.log(missing.name);
} else {
console.log("No such user");
}
// Or with optional chaining:
console.log(missing?.name ?? "No such user"); // No such user
find stops at the first match:
const numbers = [1, 5, 8, 12, 3];
const firstBig = numbers.find((n) => {
console.log(`checking ${n}`);
return n > 4;
});
// checking 1
// checking 5
console.log(firstBig); // 5
// 8, 12 and 3 were never examined.
find versus filter, said plainly:
// "Give me the user with id 2" -> find, gives the object or undefined
users.find((u) => u.id === 2);
// "Give me all users over 40" -> filter, gives an array
users.filter((u) => u.age > 40);
// Using filter for one item works and then makes you unwrap it:
users.filter((u) => u.id === 2)[0]; // clumsy, and reads all three
Pro Tip: Reach for
findwhenever you expect exactly one answer, such as looking something up by id. It says what you mean, it stops early, and it hands you the item directly instead of an array you then have to index into and hope is not empty.
EXERCISE
2findIndex, and Positions
When you need to know where an item sits rather than what it is, findIndex answers that and uses minus one for not found.
findIndex returns a position:
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Grace" },
{ id: 3, name: "Alan" },
];
console.log(users.findIndex((u) => u.id === 2)); // 1
console.log(users.findIndex((u) => u.id === 99)); // -1
Which you need for updating in place:
const i = users.findIndex((u) => u.id === 2);
if (i !== -1) {
users[i] = { ...users[i], name: "Grace Hopper" };
}
console.log(users[1].name); // Grace Hopper
The ...users[i] copies the existing fields into the new object so only name changes. Unit 8 covers that syntax properly.
Check against -1, never for truthiness:
const first = users.findIndex((u) => u.id === 1);
console.log(first); // 0
if (first) console.log("found"); // does NOT run: 0 is falsy
if (first !== -1) console.log("found"); // runs
This is the same trap as indexOf in the strings unit, for the same reason.
findLast and findLastIndex search backwards:
const numbers = [1, 5, 8, 12, 3];
console.log(numbers.find((n) => n > 4)); // 5 first match
console.log(numbers.findLast((n) => n > 4)); // 12 last match
console.log(numbers.findLastIndex((n) => n > 4)); // 3
Pro Tip: A found position of
0is perfectly valid and perfectly falsy, which is why every index-returning method in JavaScript has to be compared against-1rather than tested for truthiness. It is the same bug inindexOf,findIndexandlastIndexOf, and it hides because it only appears when the match is the first item.
EXERCISE
3includes and indexOf on Arrays
For plain values rather than objects, two simpler methods answer whether something is in the array at all.
includes answers yes or no:
const roles = ["admin", "editor", "viewer"];
console.log(roles.includes("editor")); // true
console.log(roles.includes("owner")); // false
if (roles.includes("admin")) {
console.log("Has admin rights");
}
indexOf gives the position, or -1:
console.log(roles.indexOf("editor")); // 1
console.log(roles.indexOf("owner")); // -1
Both compare with strict equality, which matters for objects:
const users = [{ id: 1 }, { id: 2 }];
console.log(users.includes({ id: 1 })); // false
// A freshly written { id: 1 } is a different object.
// For objects, use some or find instead:
console.log(users.some((u) => u.id === 1)); // true
includes finds NaN where indexOf cannot:
const values = [1, NaN, 3];
console.log(values.indexOf(NaN)); // -1 NaN is never equal to itself
console.log(values.includes(NaN)); // true includes handles this case
Choosing between the four methods in this lesson:
const roles = ["admin", "editor"];
const users = [{ id: 1, name: "Ada" }];
roles.includes("admin"); // is this value present? -> boolean
roles.indexOf("admin"); // where is this value? -> number
users.find((u) => u.id === 1); // which object matches? -> object
users.findIndex((u) => u.id === 1); // where is that object? -> number
includes and indexOf compare values directly, so they work on strings, numbers and booleans and never on objects. The moment your array holds objects, you need a callback, which means find, findIndex or some. Getting a stubborn false from includes on an array of objects is that rule making itself known.
