
The following example finds an element in the array that is a prime number (or returns undefined if there is no prime number). Examples Find an object in an array by one of its properties Using ES2015 arrow function Find a prime number in an array Elements that are deleted are still visited. Therefore, callback will not visit the elements that are appended to the array after the call to find begins. If an existing, unvisited element of the array is changed by callback, its value passed to the callback will be the given value at the time find visits that element's index. The range of elements processed by find is set before the first invocation of callback.

The find method does not mutate the array on which it is called. If it is not provided, then undefined is used. If a thisArg parameter is provided to find, it will be used as the this value for each invocation of the callback. This indicates that it may be less efficient for sparse arrays compared to other methods that only visit indexes with assigned value.Ĭallback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. callback is invoked for every index of the array from 0 to length - 1 and it is invoked for all indexes, not just those that have been assigned values. If such element is found, find immediately returns the value of that element. The find method executes the callback function once for each index of the array until it finds one where callback returns a true value. The value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned. thisArg Optional Optional object to use as this when executing callback. array Optional The array find was called upon.

index Optional The index of the current element being processed in the array. Syntax arr.find( callback(element])) Parameters callback Function to execute on each value in the array, taking three arguments:Įlement The current element being processed in the array. If you need to find the position of an element or whether an element exists in an array, use () or (). See also the findIndex() method, which returns the index of a found element in the array instead of its value. If you'd like to contribute to the interactive examples project, please clone and send us a pull request. The source for this interactive example is stored in a GitHub repository.
