Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error: Illegal return statement in JavaScript

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?

like image 321
imulsion Avatar asked Apr 17 '13 19:04

imulsion


People also ask

How to fix an Illegal return statement?

The "Illegal return statement" error occurs when the return statement is used outside of a function. To solve the error make sure to only use the return statement inside of a named or an arrow function. The statement ends a function's execution and returns the value to the caller.

Can you use return outside a function JavaScript?

The return and yield statements must be in a function, because they end (or pause and resume) function execution and specify a value to be returned to the function caller.


2 Answers

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.

like image 191
Niet the Dark Absol Avatar answered Sep 20 '22 14:09

Niet the Dark Absol


If you want to return some value then wrap your statement in function

function my_function(){    return my_thing;  } 

Problem is with the statement on the 1st line if you are trying to use PHP

var ask = confirm ('".$message."');  

IF you are trying to use PHP you should use

 var ask = confirm (<?php echo "'".$message."'" ?>); //now message with be the javascript string!! 
like image 20
prabeen giri Avatar answered Sep 20 '22 14:09

prabeen giri