;

Javascript Array - every() Method


Tutorialsrack 03/09/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.every().  How does this method work in javascript? 

Array.prototype.every()

This Array.prototype.every() is used to check whether every element fulfills the conditions by the provided function, and it returns true.

Syntax
arr.every(callback(element[, index[, array]])[, thisArg])

This method takes 5 parameters as mentioned above and described below:

  • callback: This parameter holds the function to be called for each element of the array. This function takes the mentioned parameters as below:
    • element: The parameter holds the value of the elements being processed currently.
    • index(Optional): This parameter holds the index of the current value element in the array starting from 0.
    • array(Optional): This parameter holds the complete array on which Array.every() is called.
  • thisArg(Optional): This parameter holds the context to be passed as this to be used while executing the callback function.

This method returns true if the callbackFn function returns a truthy value for every array element. Otherwise, it returns false.

The every() method does not mutate the array on which it is called.

Here are some examples of javascript’s Array every() method:

Examples
var ages = [32, 33, 12, 18, 25, 35, 40, 60];
 
/*
callback function that checks if all ages in an array
is greater than 18, if all ages greater than 18 , it returns true
otherwise it return false.
*/
function checkAdult(age) {
    return age >= 18;
}
 
console.log(ages.every(checkAdult));
// Output => false
 
 
//Another Example of every() method
 
function isBigEnough(element, index, array) {
  return element >= 10;
}
console.log([12, 5, 8, 130, 44].every(isBigEnough));
//output => false
 
console.log([12, 54, 18, 130, 44].every(isBigEnough));
//output => true
 
//Antoher Example of every() method using arrow function
//Using Arrow Function
 
console.log([12, 5, 8, 130, 44].every((x) => x >= 10)); 
//output => false
console.log([12, 54, 18, 130, 44].every((x) => x >= 10)); 
//output => true

I hope this article will help you to understand the javascript Array built-in method Array.prototype.every()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags