JS: Iterator.prototype.find

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2025)

iterator.find(f)
  • Return the first yield of iterator where the function f returns true.
  • Return undefined if not found.

f is passed args: currentElement, currentIndex.

similar to Array.prototype.find

// define a generator function
function* gf() {
 for (let x of [5, 3, 4, 3]) yield x;
}

// create a generator. a generator is both iterable and iterator
const xgenerator = gf();

// get the first even number
console.log(xgenerator.find((x, i) => (x % 2 === 0)));
// 4

// get the first yield that is 9
console.log(xgenerator.find((x, i) => (x === 9)));
// undefined