Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Bruno van der Kraan
The "Unexpected token return" error occurs when there is a syntax error in our
JavaScript code, or the return
statement is used outside of a function. To
solve the error make sure to correct any syntactical errors and only use the
return
statement inside of functions.
Here are some examples of how the error occurs.
function example(){ const a = 3, // 👈️ comma instead of semicolon return a // ⛔️ Uncaught SyntaxError: Unexpected token 'return' } 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 abc() { // ⛔️ Can't use return in expressions true && (return 'hello'); }
In the first example, we made a syntax error by using a comma instead of a semicolon.
The other examples use the return
statement outside of a function.
The last example uses the return
statement in an expression, which is not
allowed in JavaScript.
The screenshot above shows that the error occurred in the index.js
file on
line 17
.
You can also 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.
A common mistake is trying to use the return
statement inside of a loop or an
if
statement that is not in a function.
To solve the "Unexpected token return" error:
return
statement inside of functions.