1

I have been exploring Javascript generator and there is no issue in that but my doubt is how the generator is changing the value of 'const'. In my knowledge, if a variable is declared as const it can't be changed.

<script> function * numbers(i=0) { while(true){ yield ++i; } } const num = numbers(5); ///// no error console.log(num.next().value); console.log(num.next().value); console.log(num.next().value); </script> 
output 6 7 8 
3
  • 1
    because generator function returns a generator object, object's internal values can be changed even if the variable is defined with const Commented Sep 3, 2019 at 10:24
  • You can read Generator object also this generator function Commented Sep 3, 2019 at 10:27
  • num doesn't change to a different value? But of course, calling .next() can return different things on successive calls. Commented Sep 3, 2019 at 10:56

1 Answer 1

2

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 nums 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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.