Finding an Element in JavaScript

To find an element in Javascript, you can use the array.find(callback, thisValue) method. The find() method returns the first element in the array that matches the condition of the callback function. Otherwise, the method returns "undefined". The range of elements processed by the find() method is set before the first call to the callback. If the elements were added to the array after the find() method was called, then the callback function will not be called on such elements. The find() method does not change the array it was called on. In this JavaScript Array Find Element example, we use the find() method to search for a specific element within an array containing string elements. Click Execute to run the JavaScript Array Find Example online and see the result.
Finding an Element in JavaScript Execute
const fruits = ['Mango', 'Banana', 'Cherry', 'Peach', 'Apple'];

if (fruits.find(el => (el === 'Cherry'))) {
  console.log('Found');
} else {
  console.log('Not Found');
}
Updated: Viewed: 5460 times

JavaScript Array find() Method

The array.find(function(currentValue, index, array), thisValue) method in JavaScript is used to get the value of the first element in an array that matches a given condition. The find() method examines all array elements, and the first element that satisfies the condition will be returned. The find() method will not invoke a callback function on empty array elements, nor will it modify the original array.

JavaScript Array find() Syntax
array.find(function(currentValue, index, array), thisValue)

Where:
  • function: a function will be executed once for each element in the array until it returns the boolean true or reaches the end of the array. If you pass an object instead of a function, then a TypeError exception will be raised.
  • thisValue (optional): an object that can be referenced by the "this" keyword inside the callback function. If thisValue parameter is not passed, "this" will be "undefined"
JavaScript Array Find Example
let arr = [3, 6, 8, 20, 34];

let result = arr.find(element => element > 10);

console.log(result);

// output: 20

See also