×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

Array every() method with example in JavaScript

JavaScript every() method: Here, we are going to learn about the every() method of array in JavaScript.
Submitted by IncludeHelp, on March 02, 2019

JavaScript every() method

every() method is used to check a condition on all array elements (or specified elements) and returns true if all elements match the condition and return false if any element does not match the condition.

Syntax

array.every(function, [value]);

Parameters

A function name and an optional value to be tested with all elements.

Ref: JS Array every() function

Return value

true or false

Sample Input/Output

Input:
var arr1 = [10, 20, 30, 40, 50];
var arr2 = [10, 0, -20, 40, 50];

//function to check elements are positive or not
function isPositive(n){
    return n>=0;
}
    
Function call:
arr1.every(isPositive);
arr2.every(isPositive)

Output:
true
false

JavaScript Code to check whether all array elements are positive or not using Array.every() method

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>
		//function to check positive numbers
		function isPositive(n){
			return n>=0;
		}
		
		var arr1 = [10, 20, 30, 40, 50];
		var arr2 = [10, 0, -20, 40, 50];
		
		if(arr1.every(isPositive)==true)
			document.write("arr1 has all positive values<br>");
		else
			document.write("arr1 does not have all positive values<br>");

		if(arr2.every(isPositive)==true)
			document.write("arr2 has all positive values<br>");
		else
			document.write("arr2 does not have all positive values<br>");			
		
	</script>
</body>
</html>

Output

arr1 has all positive values
arr2 does not have all positive values

JavaScript Code to check whether all array elements are greater than 10 or not using Array.every() method

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>
		//function to check positive numbers
		function isPositive(n, value2test){
			return n>=value2test;
		}
		
		var arr1 = [10, 20, 30, 40, 50];
		var arr2 = [10, 0, -20, 40, 50];
		
		if(arr1.every(isPositive, 10)==true)
			document.write("arr1 has all values which are >=10<br>");
		else
			document.write("arr1 does not have all values which are >=10<br>");

		if(arr2.every(isPositive, 10)==true)
			document.write("arr2 has all values which are >=10<br>");
		else
			document.write("arr2 does not have all values which are >=10<br>");			
		
	</script>
</body>
</html>

Output

arr1 has all values which are >=10
arr2 does not have all values which are >=10

JavaScript Array Object Methods »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.