every() and some() Methods
every()
Method
Checks if all array elements pass the test provided by the callback. Returns true
or false
.
array.every((element, index, array) => {
// Callback body
});
- Does not change the original array.
- Iterates over the original array element by element.
- Returns
true
if all array elements satisfy a condition. - Returns
false
if at least one array element does not satisfy the condition. - Array iteration stops if the callback returns
false
.
// Are all elements greater than or equal to zero? - yes
[1, 2, 3, 4, 5].every(value => value >= 0); // true
// Are all elements greater than or equal to zero? - no
[1, 2, 3, -10, 4, 5].every(value => value >= 0); // false
some()
method
Checks if any array element passes the test provided by the callback. Returns true
or false
.
array.some((element, index, array) => {
// Callback body
});
- Does not change the original array.
- Iterates over the original array element by element.
- Returns
true
if at least one array element satisfies a condition. - Returns
false
if no array elements satisfy the condition. - Array iteration stops if the callback returns
true
.
// Is there at least one element greater than or equal to zero? - yes
[1, 2, 3, 4, 5].some(value => value >= 0); // true
// Is there at least one element greater than or equal to zero? - yes
[-7, -20, 3, -10, -14].some(value => value >= 0); // true
// Is there at least one element less than zero? - no
[1, 2, 3, 4, 5].some(value => value < 0); // false
// Is there at least one element less than zero? - yes
[1, 2, 3, -10, 4, 5].some(value => value < 0); // true
Array of objects
When working with an array of objects, some of their property values are checked. For example, there is an array of fruit objects, and you need to find out if all the fruits are available and if there are some fruits with availability greater than 0.
const fruits = [
{ name: "apples", amount: 100 },
{ name: "bananas", amount: 0 },
{ name: "grapes", amount: 50 },
];
// every returns true only if all fruits are greater than 0
const allAvailable = fruits.every(fruit => fruit.amount > 0); // false
// some returns true if at least one fruit is greater than 0
const anyAvailable = fruits.some(fruits => fruits.amount > 0); // true