Learn the JavaScript Array.every() and Array.some().
Array.every() and Array.some() are Javascript methods that help us to test an array against a specific condition. Firstly we will look at Array.every() and then we will see Array.some().
Array.every()
- There is a simple concept about Array.every() which is, if every element of array satisfies the condition then Array.every() returns true.
- Array.every() takes a callback function as an argument.
Let's check out how Array.every() works,
Suppose we have an array which has some numbers like:
- let numbers = [1,5,8,2,4,7];
And we have to check whether this array contains all numbers less than 10 or not. A simple way to check this is to iterate over every element and compare to 10 and return true or false. But in Array.each() we can do it like this:
- function testNumber(element) {
- return element < 10;
- }
- numbers.every(testNumber)
-
Array.some() is just like Array.every() but as its name suggests if there is any element then it returns true.
Since none of the elements in numbers array is greater than 10, its Array.some() returns false. But if we check if any number is greater than 4 then it returns true like this,
- function testNumber(element) {
- return element > 4;
- }
- numbers.some(testNumber)
-
We can also use Arrow function with Array.some() and Array.every() like this,
- numbers.every( element => element > 10)
-
Hopefully, you understand.
Thank you.