JavaScriptEasy
What is some()?
some(predicate) returns true if the callback returns a truthy value for at least one element, stopping at the first match; it returns false for an empty array.
Typical uses
- "Is there any error?":
fields.some(f => f.error). - Permission checks where any role is enough:
["admin", "owner"].some(r => user.roles.includes(r)). - Checking if a list contains an object matching a condition (where
includescannot help, because objects are compared by reference). - "Has the user changed anything?" by comparing fields.
Short-circuiting
some stops at the first truthy result, which makes it efficient. Use it instead of filter(...).length > 0, which walks the whole array and allocates a new one.
some vs find vs includes
some: you only need yes or no, with a condition.find: you need the matching item itself.includes: you are checking for an exact primitive value.
Empty arrays
[].some(anything) is false: there is no element that matches.
Logical relationship with every
list.some(fn) is equivalent to !list.every(x => !fn(x)).
Code example
js
1const fields = [2 { name: "email", error: null },3 { name: "password", error: "Too short" },4 { name: "name", error: null },5];67console.log(fields.some((f) => f.error)); // true - at least one error89const user = { roles: ["viewer", "owner"] };10const isPrivileged = ["admin", "owner"].some((r) => user.roles.includes(r));11console.log(isPrivileged); // true1213// Objects: includes can't match by content, some can14const cart = [{ sku: "A1" }, { sku: "B2" }];15console.log(cart.includes({ sku: "B2" }), cart.some((i) => i.sku === "B2")); // false true1617// Prefer some over filter(...).length18const big = Array.from({ length: 100_000 }, (_, i) => i);19let visited = 0;20const hasBig = big.some((n) => (visited++, n > 10));21console.log(hasBig, "visited only", visited); // true visited only 122223console.log([].some(Boolean)); // false - nothing matches in an empty array
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.