Open In App
Related Articles

JavaScript SyntaxError – Return not in function

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 of
missing 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


Last Updated : 22 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads