JavaScript Array every() Method
Example
Check whether all elements in the arrayagesare greater than or equal to 18:
var ages = [32, 33, 16, 40];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.every(checkAdult);
}
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.every(checkAdult);
}
The output result is:
false
Try it Yourself »
Definition and Usage
The every() method is used to check whether all elements in an array satisfy the specified condition (provided by a function).
The every() method uses the specified function to test all elements in the array:
- If an element that does not satisfy the condition is found in the array, the entire expression returnsfalse, and the remaining elements will not be tested.
- If all elements satisfy the condition, it returns true.
Note:every() does not execute the function for empty arrays.
Note:every() does not change the original array.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
| Method | |||||
|---|---|---|---|---|---|
| every() | Yes | 9 | 1.5 | Yes | Yes |
Syntax
array.every(function(currentValue,index,arr), thisValue)
Parameter Description
| Parameter | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| function(currentValue, index,arr) | Required. A function that is executed for each element in the array. Function parameters:
|
||||||||
| thisValue | Optional. An object to be used as "this" when executing the callback, passed to the function. If thisValue is omitted, the value of "this" is "undefined". |
Technical Details
| Return value: | Boolean. Returns true if all elements pass the test; otherwise, returns false. |
|---|---|
| JavaScript Version: | 1.6 |
More Examples
Example
Check whether all elements in the array ages are greater than or equal to the number specified in the input field:
<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Click me</button>
<p>Do all ages meet the condition? <span id="demo"></span></p>
<script>
var ages = [32, 33, 12, 40];
function checkAdult(age) {
return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.every(checkAdult);
}
</script>
<button onclick="myFunction()">Click me</button>
<p>Do all ages meet the condition? <span id="demo"></span></p>
<script>
var ages = [32, 33, 12, 40];
function checkAdult(age) {
return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.every(checkAdult);
}
</script>
Try it Yourself »
JavaScript Array Object