Solve - Unexpected Token 'return' Error in JavaScript


Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - Unexpected Token 'return' Error #

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.

unexpected token return

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.

You can see the exact line on which the error occurs by looking at your browser's console or your Node.js terminal.

unexpected token return

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:

  1. Correct any syntax errors in your code.
  2. Make sure to only use the return statement inside of functions.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee