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 the 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.
Javascript
let GFG = function (val) { if (val === 'GFG') return 'Text1';};/* looks like function ends here, because ofmissing opening curly bracket after 'if' keyword*/if (val === 'Geek') { return 'Text2';}console.log(GFG()); |
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.
Javascript
let GFG = function (val) { if (val === 'GFG') return 'Text1'; if (val === 'Geek') { return 'Text2'; }};return "Text3";// this is outside the function body.console.log(GFG('GFG')); |
Output(In console):
SyntaxError: 'return' statement outside of function
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



