Unexpected strict mode reserved word 'yield' in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
2 min

banner

# Unexpected strict mode reserved word 'yield' in JavaScript

The "SyntaxError: Unexpected strict mode reserved word yield" 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() { // ⛔️ SyntaxError: Unexpected strict mode reserved word 'yield' yield 10; yield 15; }

syntax error unexpected strict mode reserved word yield

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

# Add an asterisk to mark the function as a generator

Add an asterisk after the function keyword to mark a function as a generator.

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

add asterisk to mark the function as a generator

The code for this article is available on GitHub
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 marked as a generator

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

directly enclosing function has to be marked as generator

The code for this article is available on GitHub

Notice that we marked the inner function as a generator and 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.