Array every() Method - Javascript Array

Javascript examples for Array:every

Description

The every() method checks if all elements against a function by running the function once for each element present in the array:

If it finds an array element where the function returns a false value, every() returns false and does not check the remaining values

If no false occur, every() returns true.

every() does not execute the function for array elements without values.

Syntax

array.every(function(currentValue, index, arr), thisValue)

Parameter Values

Parameter Description
function(currentValue, index, arr) Required. A function to be run for each element in the array.
currentValue Required. The value of the current element
index Optional. The array index of the current element
arrOptional. The array object the current element belongs to
thisValue Optional. A value to be passed to the function to be used as its "this" value. If this parameter is empty, the value "undefined" will be passed as its "this" value

Return Value:

A Boolean. Returns true if all the elements in the array pass the test, otherwise it returns false

Check if all the values in the ages array are a specific number or over :

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>


<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>

<button onclick="myFunction()">Test</button>

<p>All ages above minimum? <span id="demo"></span></p>

<script>
var ages = [32, 33, 12, 40];/*from   w  w  w .j  a  v a 2s .  com*/

function checkAdult(age) {
    return age >= document.getElementById("ageToCheck").value;
}

function myFunction() {
    document.getElementById("demo").innerHTML = ages.every(checkAdult);
}
</script>

</body>
</html>

Related Tutorials