Array.prototype.findLoading saved progress…

Array.prototype.find

Array.prototype.find returns the first element that satisfies a test, or undefined if none does. Its sibling findLast does the same from the other end. The key distinction from findIndex is right there in the return: find hands you the matching value, not its position.

Implement find(arr, predicate, thisArg) and findLast(arr, predicate, thisArg). find scans left to right and returns the first element where predicate is truthy; findLast scans right to left and returns the last such element. Both return undefined when nothing matches.

Signature

function find(arr, predicate, thisArg) { /* first matching ELEMENT or undefined */ }
function findLast(arr, predicate, thisArg) { /* last matching ELEMENT or undefined */ }
// predicate: (value, index, array) => boolean

Examples

find([1, 2, 3, 4], (n) => n > 2);     // 3   — first element greater than 2
find([1, 2, 3], (n) => n > 10);       // undefined
findLast([1, 2, 3, 4], (n) => n < 4); // 3   — last element less than 4
find([{id:1}, {id:2}], (o) => o.id === 2); // { id: 2 }

Notes

  • Returns the element — not the index. Use findIndex when you need the position.
  • Short-circuits — stop at the first match; don't scan the rest.
  • findLast goes backward — start at the last element and move toward the first.
  • No match → undefined — not -1 (that's findIndex) and not an error.
  • Holes are visited — unlike forEach/map, find does not skip holes; a hole reads as undefined and is tested.
  • Predicate args(value, index, array), with thisArg as this when provided.
Loading editor…