Good evening. I understand the generators in ES6 and decided, for example, to write a small example of a "recursive" generator

function* f(val) { yield val; yield* f(val - 1); } const it = f(3); console.log(it.next().value); console.log(it.next().value); console.log(it.next().value); console.log(it.next().value); 

The console output surprised me a bit

  2 0 -2 -4 

As I understand it, the generator works according to the principle "reached the yield out of the generator with the object". That is, it turns out:

  1. The first line is console.log(it.next().value) Here we wake up the generator and stop at the yield val and exit the generator that will sleep before the next call. In this case, val will be equal to 3 and in the console it should output 3, respectively. Here I was originally wrong.
  2. In the second line of console.log(it.next().value) it seemed to me that we gave the generator control to ourselves, where the value of val should have become 2 and again reach the line yield val , and in the console should output the number 2. Etc. in the following paragraphs.

Help please understand where I was wrong?

  • one
    It seems everything works as it should: i.stack.imgur.com/xBm1b.png - user207618
  • This is in the console, but if you run the code, the result is the one I wrote above. - Drylozav
  • Does the console display random numbers? She also runs the code. Saving your code to a file and running it led to the same, normal result. - user207618
  • If the code does not work, it is worth adding this code to the question. as it turned out, the one that is added now - works correctly - Grundy

0