Search⌘ K
AI Features

Limitations: Generators, Exceptions, and Object Literals

Explore the limitations of arrow functions in JavaScript related to generators, exception throwing, and returning object literals. Understand syntax errors, wrapping requirements, and how to write concise code while avoiding pitfalls.

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.

Javascript (babel-node)
'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:

Javascript (babel-node)
`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 = *(start) => { //Will not work`
                          
SyntaxError: Unexpected token *

There’s no good reason for this except the support for arrow functions being ...