...

/

Limitations: Generators, Exceptions, and Object Literals

Limitations: Generators, Exceptions, and Object Literals

Learn the limitations of arrow functions while creating generators, throwing exceptions, and returning object literals.

Can’t be generators

In the Using generator in an infinite iteration section, we created a generator function that produced an infinite sequence of prime numbers. The code is repeated here for your convenience.

Press + to interact
'use strict';
//START:PRIMES
const primesStartingFrom = function*(start) {
let index = start;
while(true) {
if(isPrime(index)) yield index;
index++;
}
};
//END:PRIMES

The primesStartingFrom variable refers to an anonymous function, which is marked with * to indicate it is a generator. Since the function is anonymous, you may be tempted to replace the anonymous function with an arrow function, like this:

Press + to interact
`use strict`;
//START:PRIMES
const primesStartingFrom = *(start) => { //Will not work
//...
//END:PRIMES
let index = start;
while(true) {
if(isPrime(index)) yield index;
index++;
}
}

The code will produce the following error:

const primesStartingFrom
...
Access this course and 1400+ top-rated courses and projects.