galvin Posted January 13, 2011 Share Posted January 13, 2011 I have a function that sets two variables (var rightanswerid and var rightanswertext). At the end of that function, another function is called this way... compare(rightanswerid); Then comes the other function that does stuff with "rightanswerid" and it works fine. But within this 2nd funtion is also this line below, but it's not working (i presume because the variable doesn't stay declared from one function to the next)... document.getElementById('answer').innerHTML = rightanswertext; QUESTION: What can I do to the variable rightanswertext in the first function so that it's value carries over to the next function? Quote Link to comment Share on other sites More sharing options...
galvin Posted January 14, 2011 Author Share Posted January 14, 2011 Looks like if I don't use "var" when declaring, I can use it in the next function. It works. Is this right, i.e. if you use var it's local, if you don't, it's global? Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 14, 2011 Share Posted January 14, 2011 Your problem has to do with variable scope. A variable created/used in one function is not the same as another variable of the same name in another function - UNLESS the variables are declared as global. Different programming languages can handle variable scope differently. For JavaScript any variable declared outside of a function will be global. Variables declared inside functions are not. You can, however, pass variables into a function as needed. Whether you should use a global variable or just pass them to the needed functions depends greatly on the context. I'd suggest doign a google seach for "Javascript variable scope" for more resources. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.