Array .some() / every()
| Since: | ES5(ECMAScript 2009) |
|---|
Methods that check whether elements in an array satisfy a condition. some() returns true if at least one element satisfies the condition; every() returns true only if all elements satisfy the condition.
Syntax
var result = array.some(function(element, index, array) {
return condition;
});
var result = array.every(function(element, index, array) {
return condition;
});
Method List
| Method | Description |
|---|---|
| some(function) | Returns true if at least one element in the array satisfies the condition. Returns false if no elements satisfy the condition. Always returns false for an empty array. |
| every(function) | Returns true if all elements in the array satisfy the condition. Returns false if any element does not satisfy the condition. Always returns true for an empty array. |
Sample Code
var scores = [65, 80, 42, 90, 75];
var hasExcellent = scores.some(function(score) {
return score >= 90;
});
console.log(hasExcellent); // Outputs: true
var allPassed = scores.every(function(score) {
return score >= 50;
});
console.log(allPassed); // Outputs: false — 42 does not meet the condition.
// Example: validating form fields.
var fields = ["admin", "user1@example.com", ""];
var hasEmpty = fields.some(function(field) {
return field === "";
});
console.log(hasEmpty); // Outputs: true — there is an empty field.
var allFilled = fields.every(function(field) {
return field !== "";
});
console.log(allFilled); // Outputs: false
true false true false
Overview
array.some() and array.every() are methods for evaluating a condition against an entire array. Both use short-circuit evaluation — they stop iterating as soon as the result is determined. array.some() stops when it finds an element that returns true; array.every() stops when it finds an element that returns false. This makes both methods efficient even for large arrays.
For form validation, you can use array.every() to confirm that all fields are filled in, and array.some() to detect whether any field is empty. Both methods are also useful for permission checks and conditional branching.
Be aware of how these methods behave with empty arrays. array.some() always returns false for an empty array, while array.every() always returns true. This behavior is based on the concept of "vacuous truth" in mathematical logic. If you need to retrieve the matching elements themselves rather than just a boolean result, use array.find() / array.filter().
Browser Compatibility
1 or earlier ×
2 or earlier ×
8 or earlier ×
9 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.