Solve - Unexpected Strict mode reserved word 'yield' in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20211 min read

banner

Photo by Resa Cahya

Solve - Unexpected Strict mode reserved word 'yield' #

The "Unexpected strict mode reserved word yield" error occurs when the yield keyword is used outside of a generator function. To solve the error, mark the function as a generator by appending an asterisk to the function keyword, e.g. function* generator() {}.

unexpected strict mode reserved word yield

Here's an example of how the error occurs.

index.js
function example() { // ⛔️ Unexpected strict mode reserved word 'yield' yield 10; yield 15; }

We used the yield keyword inside of a function we didn't mark as a generator.

To declare a function as a generator, append an asterisk to the function keyword.

index.js
// ✅ works function* generator() { yield 10; yield 15; } const gen = generator(); console.log(gen.next().value); // 👉️ 10 console.log(gen.next().value); // 👉️ 15
Note that arrow functions cannot be declared as generators. You can only use the yield keyword inside of named functions that were declared as generators.

The directly enclosing function has to be a generator for you to be able to use the yield keyword.

Here's an example of nested functions.

index.js
function generator() { return function* inner() { yield 10; yield 15; }; } const gen = generator()(); console.log(gen.next().value); // 👉️ 10 console.log(gen.next().value); // 👉️ 15

Notice that we marked the inner function as a generator, not the outer one.

This is because we use the yield keyword inside of the inner function.

To be able to use the yield keyword, declare the directly enclosing function as a generator.
Use the search field on my Home Page to filter through my more than 1,000 articles.