How to use array every in JavaScript
In this article I am going to explain every() in JavaScript.
Every method in JavaSript
JavaScript every method checks whether a define callback function returns true for all element in an array.
Syntax of every method
array.every(callback[, thisArgs);
|
Parameters in every method:
-
arrary
Array required an array object.
-
callback
Callback function accepts up to three arguments, and callback function is used to test for each element
-
thisArgs
ThisArgs is used as this when executing callbacks.
Return value in every method
It returns true if callback function is returned true for all array element, otherwise it returns false.
Exception in every method
If callback argument is not a function object, A TypeError exception is fire.
There are the following callback parameter:
Parameter |
Value |
value |
Array element value. |
index |
Number of index of the array element. |
Example of every method
<html>
<head>
<title>JavaScript every method</title>
</head>
<body>
<script type="text/jscript">
function CheckIfEven(value, index, ar) {
document.write(value + " ");
if (value % 2 == 0)
return true;
else
return false;
}
var numbers = [2, 4, 5, 6, 8];
if (numbers.every(CheckIfEven))
document.write("All are even.");
else
document.write("Some are not even.");
</script>
</body>
</html>
|
Output:
Ask Your Question
Got a programming related question? You may want to post your question here