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.
Case 1: Return
Statement Outside of Function
Error Cause:
The most common cause is using the return
statement outside of a function, which leads to a syntax error.
Example:
return 5; // Incorrect usage, not inside a function
Output:
SyntaxError: Illegal return statement
Resolution of Error:
Ensure that the return
statement is inside a function.
function exampleFunction() {
return 5; // Correct usage, inside a function
}
console.log(exampleFunction()); // Outputs: 5
Output
5
Case 2: Misplaced Return
in Global Code
Error Cause:
Another cause is placing the return
statement in the global scope or in an incorrect context.
Example:
return "Hello, world!"; // Incorrect usage, in the global scope
Output:
SyntaxError: Illegal return statement
Resolution of Error:
Move the return
statement into a function.
function greet() {
return "Hello, world!"; // Correct usage, inside a function
}
console.log(greet()); // Outputs: Hello, world!
Output
Hello, world!
Case 3: Return
Statement in a Non-function Block
Error Cause:
Using a return
statement inside blocks that are not functions, such as conditionals or loops, will also result in an error.
Example:
if (true) {
return "This will cause an error."; // Incorrect usage, inside an if block
}
Output:
SyntaxError: Illegal return statement
Resolution of Error:
Ensure that the return
statement is used only within a function.
function checkCondition() {
if (true) {
return "Condition met"; // Correct usage, inside a function
}
}
console.log(checkCondition()); // Outputs: Condition met
Output
Condition met