if a variable is declared as const it can't be changed.
What it refers to cannot be changed, it does not control the return values of functions or the mutability of objects.
In this specific case const num = numbers(5)
assigns a generator object to num
, now num
will always refer to that same generator object, but that's where const's control ends - As soon as you start digging into num
s properties (the next()
method) you have left the initial reference behind, now you are using a different reference (next
method on the num
object), which returns another completely independent object with a property value
- that is three references away from the original.
Even if you forgo all of the intermediate objects, const still has no control over a function's return value:
let i = 0;
const foo = () => i ++;
foo(); // 0
foo(); // 1
foo(); // 2
const is about assignment, it only prevents this:
const foo = () => i ++;
const foo = () => 0;
// SyntaxError: Identifier 'foo' has already been declared
Generators are no different in this respect, they just have some special internal flow control.