Tutorialspoint.dev

JavaScript | Array every() function

Array.every() function checks whether all the elements of the array satisfy the given condition or not that is provided by a function passed to it as the argument. The syntax of the function is as follows:

arr.every(function[, This_arg])

Argument
The argument to this function is another function that defines the condition to be checked for each element of the array. This function argument itself takes three arguments:

  • array (optional)
  • This is the array on which the .every() function was called.

  • index (optional)
  • This is the index of the current element being processed by the function.

  • element (Compulsory)
  • This is the current element being processed by the function.

Another argument This_arg is used to tell the function to use this value when executing argument function.



Return value
This function returns Boolean value true if all the elements of the array follow the condition implemented by the argument function. If one of the elements of the array does not satisfy the argument function, then this function returns false.

Examples for above function are as follows:

Example 1:

function ispositive(element, index, array) {
  return element > 0;
}
print([11, 89, 23, 7, 98].every(ispositive)); 

Output:

true

In this example the function every() checks if a number is positive for every element of the array. Since the array does not contain negative elements therefore this function returns true as the answer.

Example 2:

function isodd(element, index, array) {
  return (element % 2 == 1);
}
print([56, 91, 18, 88, 12].every(isodd)); 

Output:

false

In this example the function every() checks if every number in the array is odd or not. Since some of the numbers are even, therefore this function returns false.

Codes for above function are as follows:

Program 1:

<script>
// JavaScript code for every() function
function ispositive(element, index, array) 
{
   return element > 0; 
}
  
function func() {
  var arr = [ 11, 89, 23, 7, 98 ];
    
  // check for positive 
  // number
  var value = arr.every(ispositive);
  document.write(value);
}
func();
</script>

Output:

true

Program 2:

<script>
// JavaScript code for every() function
function isodd(element, index, array)
   return (element % 2 == 1); 
}
  
function func() 
{
   var arr = [ 56, 91, 18, 88, 12 ];
    
   // check for odd number
   var value = arr.every(isodd);
   document.write(value);
}
func();
</script>

Output:

false


This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter