Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Roberto Nickson
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.
Here are examples of when the error occurs.
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.
function test() { if (true) { return 100; } return 200; }
Another common reason of the error being thrown is a syntax error in our code.
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:
return
statement inside of functions.