In this article, you will learn about the javascript Array built-in method Array.prototype.every()
. How does this method work in javascript?
This Array.prototype.every()
is used to check whether every element fulfills the conditions by the provided function, and it returns true
.
arr.every(callback(element[, index[, array]])[, thisArg])
This method takes 5 parameters as mentioned above and described below:
Array.every()
is called.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:
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!
Comments