DEV Community

Discussion on: Create our own iterable in JavaScript

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

Can I make it as easy as Python's def __iter__(self) and yield?

I know there is yield in JavaScript somewhere, but I never used it.

Collapse
 
ussdlover profile image
Alireza Razinejad

Not that much easy.
But we can do something like this

/**
 * @param val
 * @returns {Generator<*, void, *>}
 */
function* ourOwnInterable(val) {
    while (val < 3) {
        yield val;
        val++;
    }
}

/**
 * @type {Generator<*, void, *>}
 */
const iterator = ourOwnInterable(0);

for (const el of iterator) {
    console.log(el);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
badreddine11 profile image
ABDELLAOUI

Hi

Collapse
 
reykcs profile image
Reyk • Edited

Wow im programming with javascript since like 4 years and i have never used nor seen those generator functions. So definitely thank you for this hint!

Always thought the usage of the asterisks in declarations is limited to pointers in c and c++ 😅