Click to See Complete Forum and Search --> : passing variables between functions


webmark
11-21-2002, 08:14 PM
i know this question is relatively easy, but please do help me

i need to pass a variable from two functions, i.e.

function smile(big, happy){
me=happy;
.
.
.}
function sad(){
alert(me);
}

enderl25
11-21-2002, 09:10 PM
webmark,

to pass a value from one function to another,
pass the value as a parameter of the function call.

as follows:
---------------------------------------------------
function smile () // function header
{
var me; // variable declaration

sad (me); // function call ( with parameter )

return; // return program control to calling function
}

function sad (me) // function header
{
alert (me); // output value to the terminal

return; // return program control to calling function
}
----------------------------------------------------

if you simply need to access a variable from inside of multiple functions,
declare the variable outside of all functions, thus making it a global variable.
then you will be able to access it from with any subsequent funcitons

as follows:
-----------------------------------------------------
var me;

function smile ( )
{
me = 'big';

alert (me);

return;
}

function sad ()
{
me = 'happy';

alert (me);

return;
}
------------------------------------------------------

hope this helps

ritz

Beach Bum
11-21-2002, 10:14 PM
I think there is a simple answer to your question.

If you have defined a variable, you can use it in as many functions as you want. Its value stays at what ever it was last. You will note that you generally define a variable outside of the function in the first place, then use it in a function. There is no association between a function and a variable per se. So feel free to use a variable in more than one function.

<script . . . .
var whatever
function number1()
...
function number2()
...
</script>

both functions can use variable whatever

Is that what you are asking?