when I try the following:
if(myFunction() == "3") {
alert('its three!');
}
my function returns undefined, when I know that it is actually returning 3.
Is this because javascript evaluates the if statement before the function can return a value?
if so how can I do something like this:
var result = myFunction();
// Wait until result is there
if(result == "3") {
alert("its three!");
}
What it sounds like is that your javascript code is calling the function before the function or the elements it accesses (ie something in the DOM) have been fully loaded, which is why the function call is returning undefined instead of ‘3’.
The way to prevent this is to defer calling the function until the DOM has finished loading.
This is typically done by having the function call in your
document.onload()method, which only gets run when the page has finished loading, or by using jQuery’s$.ready()method, which again waits until the page is ready before being run.Hope that helps.