Solve - Illegal return statement Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - Illegal return statement Error #

The "Illegal return statement" error occurs when the return statement is used outside of a function. To solve the error make sure to only use the return statement inside of a named or an arrow function. The statement ends a function's execution and returns the value to the caller.

illegal return statement

Here are examples of when the error occurs.

index.js
return 5; // 👈️ return outside function if (true) { // 👈️ return outside function return 10; } for (let i = 0; i < 3; i++) { // 👈️ return outside function return 15; } function example() // 👈️ missing { return true }

The most common cause of the "Illegal return statement" error is using the return statement outside of a function.

The if statement or for loop are not inside of a function, therefore we're not allowed to use the return statement in them. Instead, you should wrap the if statement in a function.

index.js
function test() { if (true) { return 100; } return 200; }

Another common reason of the error being thrown is a syntax error in our code.

You can check on which line of your code the error was thrown by opening your browser's console or your Node.js terminal.

illegal return statement

In the screenshot, we can see that the error was thrown in the index.js file on line 5.

If you don't see any syntax errors that might be causing the error and your return statement is inside of a function, paste your code into an online Syntax Validator. The validator should be able to tell you on which line the error occurs.

You can hover over the squiggly red line to get additional information on why the error was thrown.

To solve the "Illegal return statement" error:

  1. Make sure to only use the return statement inside of functions.
  2. Correct any syntax errors in your code.
Use the search field on my Home Page to filter through my more than 1,000 articles.