Skip to content

SyntaxError: Illegal return statement

Error message

                Illegal return statement
              

Quick summary

You used `return` outside of a function body — return is only valid inside functions.

Why this happens

  • Used return at the top level of a script (not inside a function)

  • Used return inside an if block that is not inside a function

  • Accidentally placed a return statement outside the function body

Minimal example

✗ Broken code
const x = 5;
return x;
✓ Fixed code
function getValue() {
  const x = 5;
  return x;
}

return is only valid inside a function. Wrap the code in a function to use return.

How to diagnose

  • Find the return statement mentioned in the error

  • Check if it is inside a function body

  • Look for misplaced return statements in the code structure

How to fix

  • Move the return statement inside a function

  • Remove the return if it was not intended to be in a function

  • Wrap the code in a function if the return is needed

How to prevent

  • Always use return inside function bodies only

  • Use a linter to catch illegal return statements

Related Resources

Related Glossary

Related Lessons

← Back to language