Jump to content

using two variables in another function?


galvin

Recommended Posts

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?

 

Link to comment
https://forums.phpfreaks.com/topic/224370-using-two-variables-in-another-function/
Share on other sites

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.