JS Array find & findIndex

Array find() Method

The Javascript arr.find() method in Javascript is used to get the value of the first element in the array that satisfies the provided condition. It checks all the elements of the array and whichever the first element satisfies the condition is going to print. This function will not work function having the empty array elements and also does not change the original array.

Syntax:

array.find(function(currentValue, index, arr),thisValue);

Parameters: This method accepts 5 parameters as mentioned above and described below:

Return value: It returns the array element value if any of the elements in the array satisfy the condition, otherwise it returns undefined.
 

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript</title>
  <script>
    var ages = [10, 23, 19, 20];
	document.write(ages + "<br>");
	
	var b = ages.find(checkAdult);
	document.write(b + "<br>");

	function checkAdult(age) {
		return age >= 18;
	}
  </script>
</head>
<body>
</body>
</html>

Array findIndex() Method

The Javascript Array.findIndex() method is used to return the first index of the element in a given array that satisfies the provided testing function (passed in by the user while calling). Otherwise, if no data is found then the value of -1 is returned.

Syntax:

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

Parameters: This method accepts five parameters as mentioned above and described below:

Return value:  It returns the array element index if any of the elements in the array pass the test, otherwise, it returns -1.
<!DOCTYPE html>
<html>
<head>
  <title>JavaScript</title>
  <script>
    var ages = [10, 12, 23, 20];
	document.write(ages + "<br><br>");
	
	var b = ages.findIndex(checkAdult);
	document.write(b + "<br>");

	function checkAdult(age) {
			return age >= 18;
		}
  </script>
</head>
<body>
</body>
</html>