Check if every element of array satisfies a condition in JavaScript
In JavaScript, Array.every()
function is used to check if every element of array satisfies a given criteria represented by a function.
Syntax
array.every( function, thisValue )
array
is the given array.every
is inbuilt array method name.function
a function to run for every element. the definition of the function isfunction(element, index, arr)
. the function must return a boolean value oftrue
orfalse
.element
is the current element in the array.index
of the current element [optional argument].arr
is the array of current element [optional argument].
this
is a value passed to the function as its this value [optional argument].
every()
method returns true
if all the elements of the array return true
for the given function. If there is at least one element that returns false
, then every()
method returns false
for the array.
Examples
1. Check if all the strings in the given array fruits
are non-empty.
function isNonEmptyString(x) {
if (x.length != 0) {
return true;
} else {
return false;
}
}
let fruits = ['apple', 'banana', 'cherry'];
let output = fruits.every(isNonEmptyString);
console.log(output);
2. fruits
have an empty string. Check if the output of every()
when the isNonEmptyString()
function returns false for an empty string.
function isNonEmptyString(x) {
if (x.length != 0) {
return true;
} else {
return false;
}
}
let fruits = ['apple', '', 'cherry'];
let output = fruits.every(isNonEmptyString);
console.log(output);
3. Check if all the numbers in array are even.
function isEven(num) {
if (num % 2 == 0) {
return true;
} else {
return false;
}
}
let numbers = [4, 10, 8, 18];
let output = numbers.every(isEven);
console.log('Are all numbers even? : ' + output);