Loops in generators in JavaScript

Loops can be used inside generators. At the same time, we can pause loops with yield. Let's look at an example. We will pause the loop every iteration:

function *func() { for (let i = 1; i <= 3; i++) { yield i; } }

We get an iterator:

let iter = func();

Let's test our iterator:

console.log(iter.next()); // {value: 1, done: false} console.log(iter.next()); // {value: 2, done: false} console.log(iter.next()); // {value: 3, done: false} console.log(iter.next()); // {value: undefined, done: true}

Create an iterator, each call of which will return numbers from 10 to zero.

Make a generator that takes a number as a parameter. Let each iterator call decrease the number by one until zero is reached.

Make a generator that takes a number as a parameter. Let each iterator call decrease the number by half and return the result. And so on, until the number becomes less than one.

Make an iterator, each call of which will return the next power of two.

Make an iterator, each call of which will return the next Fibonacci number.

enru