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.
<!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 > |
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.
<!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 > |
Output(In console):
SyntaxError: 'return' statement outside of function