JavaScript SyntaxError – Return not in function

This JavaScript exception return (or yield) not in function occurs if a return/yield statement is written outside the body of function.

Message:

SyntaxError: 'return' statement outside of function (Edge)
SyntaxError: return not in function (Firefox)
SyntaxError: yield not in function (Firefox)

Error Type:

SyntaxError

What happened?

Either the return or yield statement is called outside the body of the function or there might be a missing curly bracket in the code.



Example 1: In this example, there is a missing curly bracket after the ‘if’ statement, so the error has occurred.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<head>
<title>Syntax Error</title>
</head>
<body>
    <script>
    var GFG = function(val) {
      if (val === 'GFG')
        return 'Text1';
      }; 
       /* looks like function ends here, because of
       missing opening curly bracket after 'if' keyword*/
      if (val === 'Geek') {
        return 'Text2';
      }
    }
    document.write(GFG());
    </script>
</body>
</html>

chevron_right


Output(In console):

SyntaxError: 'return' statement outside of function

Example 2: In this example, the return statement is written after the function has ended, So the error has occurred.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<head>
<title>Syntax Error</title>
</head>
<body>
    <script>
    var GFG = function(val) {
      if (val === 'GFG')
        return 'Text1';
      if (val === 'Geek') {
        return 'Text2';
      }
    };
    return "Text3"; 
  // this is outside the function body.
    document.write(GFG('GFG'));
    </script>
</body>
</html>

chevron_right


Output(In console):

SyntaxError: 'return' statement outside of function

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.