find()

The find method in JavaScript arrays retrieves the initial element from the specified array that meets the criteria defined by the supplied function.

Syntax

The syntax for the find method is illustrated as follows:

Example

array.find(callback(value,index,arr),thisArg)

Parameter

callback - It signifies the function that processes every individual element.

value - The current element of an array.

index - This parameter is optional. It refers to the index of the current element.

arr - This parameter is optional. It represents the array that the find function is applied to.

thisArg - This parameter is not mandatory. It specifies the value that should be utilized as this during the execution of the callback function.

Return

The value of the initial element in the array that meets the criteria set by the function condition.

JavaScript Array find method example

Let's see some examples of find method.

Example 1

Let's see a simple example of find method.

Example

<script>

var arr=[5,22,19,25,34];

var result=arr.find(x=>x>20);

document.writeln(result)

</script>

Output:

Example 2

In this illustration, we will identify a prime number by utilizing the find method.

Example

<script>

function isPrime(value, index, arr) {

  var start = 2;

  while (start <= Math.sqrt(value)) {

    if (value % start++ < 1) {

      return false;

    }

  }

  return value > 1;

}

document.writeln([8, 4, 7, 22].find(isPrime));

</script>

Output:

Input Required

This code uses input(). Please provide values below: