How to Use some and every in JavaScript
Checking if any or all items in an array pass a test.
There are times when you don't need the matching items from an array, you just
need a yes or no answer, like whether any item in the cart is out of stock or
whether every field in a form has been filled out. The some and every
methods give you that answer.
some() returns true if at least one item passes your test. every()
returns true only if all of them do.
Using some
some runs your callback on each item and returns true as soon as one of them
returns a truthy value:
const cart = [{ name: "Keyboard", inStock: true },{ name: "Mouse", inStock: false },{ name: "Monitor", inStock: true },]const hasOutOfStock = cart.some((item) => !item.inStock)console.log(hasOutOfStock) // true
It stops checking once it finds a match, so the Monitor is never looked at.
Using every
every is the opposite. It returns true only if your callback returns a
truthy value for every single item, and stops at the first one that fails:
const fields = [{ name: "email", value: "pam@dundermifflin.com" },{ name: "password", value: "" },]const isComplete = fields.every((field) => field.value !== "")console.log(isComplete) // false
A Practical Example
These work great for enabling or disabling things in a UI. Here we only let someone check out when every item is in stock:
const button = document.querySelector("#checkout")button.disabled = !cart.every((item) => item.inStock)
And here we show a warning if any password rule fails:
const password = "hunter2"const rules = [(value) => value.length >= 8,(value) => /[0-9]/.test(value),(value) => /[A-Z]/.test(value),]const isWeak = rules.some((rule) => !rule(password))// true
Empty Arrays
One thing to watch for is what happens with an empty array:
;[].some((item) => item > 0) // false;[].every((item) => item > 0) // true
every returns true because there's nothing that fails the test. That's
technically correct, but it can surprise you. If an empty list should count as
"not done", check the length too:
const allDone = todos.length > 0 && todos.every((todo) => todo.done)
Both methods read almost like plain English, which makes conditions a lot easier to understand at a glance than a loop with a flag variable.
Have some feedback on this post? .