To troubleshoot your problem, try calling the "alert" function with the return value of your function as the argument:
var result = myFunction(); // For debugging alert(result); if(result == "3") { alert("its three!"); }
If the contents of the alert box are "undefined", your function is not in fact returning a value, and just assigning that non-existent result to a variable is not going to help. Check to make sure myFunction looks like:
function myFunction() { // Perform calculations var n = 10 - 7; // Return result return n; }
The JavaScript interpreter requires neither functions to return values nor return statements to be used. That means you should double-check that there is in fact a return statement. If you are assigning the result to a variable first, that can be one way you could miss that return statement.
If you are dealing with Ajax requests, jQuery "modal dialogs," or similar constructs, it is not even possible for a function to return a value in this way (when the button is clicked or the request completes, that is). To fix the problem, your function needs to accept a callback function as a parameter. Then when done, it must call that function, passing the "returned value" as an argument:
function myFunction(callback) { // Start an AJAX request var x = new XMLHttpRequest(); x.open('GET', '/domath.php?expression=10-7', true); x.onreadystatechange = function() { if(x.readyState == 4 && x.status == 200) { // Call callback function, "returning" a value asynchronously callback(x.responseText); } }; x.send(); }
And then your main code would be:
myFunction(function(result) { // For debugging alert(result); if(result == "3") { alert("its three!"); } });