Question
When should I use the .every()
method vs the .some()
method?
Answer
We can use the .every()
method when we want to check if a condition is true
for each element in an array, if an element does not pass our test provided to the .every()
method, .every()
will return false
- meaning that at least one element in the array did not pass our test.
For example:
var myArray = [4, 7, 2, 19, 9];
function isBelowTen(num) {
return num < 10; //returns a boolean value - true if num is less than 10, false if num is equal to or greater than 10
}
myArray.every(isBelowTen); //returns false because one of the elements in the array did not pass our test
We can use the .some()
method instead when we want to check if some of the elements in our array pass a given test, if an element passes the given test, .some()
will return true
- meaning that at least one element in the array passed our test.
For example:
var myArray = [4, 7, 10, 42, 9];
function isGreaterThanTen(num) {
return num > 10; //returns a boolean value - true if num is greater than 10, false if num is equal to or less than 10
}
myArray.some(isGreaterThanTen); //returns true because at least one of the elements in the array passes our test