JavaScript Array: every() Method

JavaScript Array: every() Method

Sometimes we need to take an array and apply some method(s) to its elements so that we get a new array with modified elements.

Here in this module we will discuss the every() method of the JavaScript array.

By the name of this method, we can understand one thing is it is directly related to every element of the array. every() is one of the most important Array methods to the developer while making some important condition check. This method takes a callback function that performs a test to checks that each element of the array pass some given condition. This method will return true or false after checkings all elements of the array.

Point to remember
1. This method takes a callback function to perform the test.
2. Check if all the elements pass the test.
3. It will return True if all the elements pass the test.
4. It will return False if any/all of the elements fail the test.

Let's understand this with a few examples.

ages = [70,17,23,50,33];
Check if all the ages of the ages array are more than 15.

var ages = [70,17,23,50,33];
// Now creating a callback function which will check all elements
function checkAge(x){
    return x>15; //this will return true/false;
}
var result = ages.every(checkAge);
console.log(result); // -> true;

Q. A class test, Martha got in math 80, in science 83, in Arts 79, in computer 92, in history 72. Now how to check if she got more than or equal 75 in all subjects?
Ans.

var numbers = [80,83,79,92,72];
function checkNumbers(x){
   return x >=75;
}
console.log(numbers.every(checkNumbers)); // -> false;

Achieving this in arrow function:

var numbers = [80,83,79,92,72];
var result = numbers.every((x) => x >= 75);
console.log(result);  // -> false;

Did you find this article valuable?

Support Bibhas by becoming a sponsor. Any amount is appreciated!