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
Manu
  • 711
  • 8
  • 27
  • 1
    because generator function returns a `generator` object, object's internal values can be changed even if the variable is defined with const – Code Maniac Sep 03 '19 at 10:24
  • You can read [`Generator object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator) also this [`generator function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) – Code Maniac Sep 03 '19 at 10:27
  • `num` doesn't change to a different value? But of course, calling `.next()` can return different things on successive calls. – Bergi Sep 03 '19 at 10:56

1 Answers1

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.

Thomas Brierley
  • 1,187
  • 1
  • 7
  • 8