Open In App

JavaScript SyntaxError - Return not in function

Last Updated : 15 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
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.

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.

JavaScript
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.

JavaScript
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.

JavaScript
function checkCondition() {
    if (true) {
        return "Condition met"; // Correct usage, inside a function
    }
}
console.log(checkCondition()); // Outputs: Condition met

Output
Condition met



Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy