Here, we will see the difference between every() and some() methods in JavaScript.
Array.every() method
The Array.every() method in JavaScript is used to check whether all the elements of the array satisfy the given condition.
- Returns false if even one element does not satisfy the condition.
- Returns true only if all elements satisfy the condition.
Syntax:
// Arrow function
every((element) => { /* … */ })
every((element, index) => { /* … */ })
every((element, index, array) => { /* … */ })
Example: This example implements the every() method.
// JavaScript code for every() function
function isodd(element, index, array) {
return (element % 2 == 1);
}
function geeks() {
let arr = [6, 1, 8, 32, 35];
// check for odd number
let value = arr.every(isodd);
console.log(value);
}
geeks();
Array.some() method
The Array.some() method in JavaScript is used to check whether at least one of the elements of the array satisfies the given condition.
- Returns
trueif at least one element satisfies the condition. - Returns
falseif no elements satisfy the condition.
Syntax:
arr.some(callback(element,index,array),thisArg);Example: This example implements the some() method.
// JavaScript code for some() function
function isodd(element, index, array) {
return (element % 2 == 1);
}
function geeks() {
let arr = [6, 1, 8, 32, 35];
// check for odd number
let value = arr.some(isodd);
console.log(value);
}
geeks();
Array.every() vs Array.some()
| Array.every() | Array.some() |
|---|---|
| The Array.every() method is used to check whether all the elements of the array satisfy the given condition or not. | The Array.some() method is used to check whether at least one of the elements of the array satisfies the given condition or not. |
| The every() method will return true if all predicates are true | The some() method will return true if any predicate is true |
| This method executes a function for each array element. | This method does not execute the function for empty array elements. |
Its Syntax is: array.every(function(value, index, array), this) | Its syntax is: array.some(function(value, index, array), this) |