JavaScriptArrays
Array. prototype. every()
Checks whether all elements match a condition.
- Returns
trueif every element passed the test, otherwisefalse.- Changes the original
- No
Example
#JavaScript
const tasks = [{ done: true }, { done: true }, { done: false }]
console.log(tasks.every((task) => task.done))
console.log(tasks.slice(0, 2).every((task) => task.done))
console.log([].every(() => false))Console
false
true
true
Definition and usage
#The every() method returns true only when the testing function returns a truthy value for every element. On the first element that fails the test, it stops and returns false.
It works well for validation: are all fields filled in, are all tasks in a module complete, is every number positive.
For an empty array, every() returns true. That’s logically consistent (there’s no element that breaks the condition), but it can be surprising, so with empty data it’s worth checking the length separately.
Syntax
#Syntax
array.every(callbackFn)
array.every(callbackFn, thisArg)Parameters
#callbackFn
function (element, index, array)
The testing function.thisArg
optional
Thethisvalue inside the function.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Watch out for an empty array:
[].every(...)returnstrue. If an empty list should mean an error for you, checklengthtoo. - The
every()andsome()pair covers most "do all" and "does any" questions.
Related entries
#Spotted a mistake or missing an example? Write to us.