find method

The find method helps to find the first element in an array according to the callback passed in the parameter. If there is no element, then undefined is returned.

Syntax

javascriptarray.find(function);

Example

Let's find the array element that matches the conditions specified in a function:

javascriptlet arr = [1, 2, 3, 4];

let res = arr.find(function(currentValue) {
  return currentValue > 0;
});

console.log(res);

The code execution result:

javascript1

Example

Let's find an array element whose length is 2:

javascriptlet arr = ['abc', 'defg', 'kl', 'mn'];

let res = arr.find(function(elem) {
  return elem.length == 2;
});

console.log(res);

As a result of executing the code, we will see that the method found the first element that matches the conditions of the function:

javascript'kl'

See also

  • the findIndex method
    that searches for the index of an element in an array
  • the findLast method
    that searches for an element from the end of an array
  • the findLastIndex method
    that searches for the index of an element from the end of an array