Syntax error: Illegal return statement in JavaScript

imulsion picture imulsion · Apr 17, 2013 · Viewed 131.2k times · Source

I am getting a really weird JavaScript error when I run this code:

<script type = 'text/javascript'>
var ask = confirm('".$message."');
if (ask == false)
{
    return false;     
}

else
{
    return true;
}
</script>

In the JavaScript console it says:

Syntax Error: Illegal return statement

It occurs at return true; and return false;

(I am echoing this javascript from a php function; the $message variable is one of the php parameters)

What is wrong with my code?

Answer

Niet the Dark Absol picture Niet the Dark Absol · Apr 17, 2013

return only makes sense inside a function. There is no function in your code.

Also, your code is worthy if the Department of Redundancy Department. Assuming you move it to a proper function, this would be better:

return confirm(".json_encode($message).");

EDIT much much later: Changed code to use json_encode to ensure the message contents don't break just because of an apostrophe in the message.