Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

271
Views
Uncaught TypeError: element is undefined when using generator function

I have the following javascript snippet:


/**
 *  Returns the maximal element in the `iterable` as calculated by the given function
 *  @param {Iterable} iterable - iterable to find the maximal element in
 *  @param {function} fn - function to calculate the maximal element
 * 
 *  @returns {any} - maximal element in the `iterable`
 */
function maxBy(iterable, fn) {
    let maximalElement = iterable[0];
    for (let element of iterable) {
        if (fn(element) > fn(maximalElement)) {
            maximalElement = element;
        }
    }
    return maximalElement;

}


// example generator function
generator = function* ()  {
   yield [3,4]
   yield [4,6]
}
maxBy(generator(), element => element[1])

When I run this in browser console, I get Uncaught TypeError: element is undefined error and I can't seem to spot where's the error in my code.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You cannot use iterable[0] to access the first element in a generator. You'll need to get the iterator and iterate it:

function maxBy(iterable, fn) {
    const iterator = iterable[Symbol.iterator]();
    const first = iterator.next();
    if (first.done) return;
    let maximalElement = first.value;
    for (let element of iterator) {
        if (fn(element) > fn(maximalElement)) {
            maximalElement = element;
        }
    }
    return maximalElement;
}

Alternatively, just initialise maximalElement with undefined, this might happen anyway if the iterable is empty:

function maxBy(iterable, fn) {
    let maximalElement;
    for (let element of iterable) {
        if (maximalElement === undefined || fn(element) > fn(maximalElement)) {
            maximalElement = element;
        }
    }
    return maximalElement;

}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!