View Full Version : Best way to retrieve variable from one function and use it in another

03-23-2012, 05:16 PM
Hi, I know there are several ways to do this- but which way is best practice?

I can access a variable from one function by making it a global variable, but I read that this isn't the most ideal way, and is a last resort. So for example if I have this:

function num1(){
var firstNum = 35;
return firstNum;

function num2(){
var secNum = 52;
return secNum;

function addNums(x,y){
var f = num1(x);
var s = num2(y);
var total = f + s;

Then I call this function with a button.

Now, I know this works, but it doesn't seem like a very good way to do what I'm after. Or is it?
Any help/ tips would be great.

edit: The idea is that the functions won't just return a single value and that's it. They will return a users choice in a given scenario, so they might return the user's
age from the first function, then their location in the next etc etc, then I want to use this information in a separate function.

Old Pedant
03-23-2012, 05:25 PM
It is the best way.

Leave it alone.

03-23-2012, 08:51 PM
Thanks mate.
Another quick question.

globalNumber = 12;

//can't grab this number and use it in the onClick part
//down below.
function ranNum(){
globalNumber = 12;

function addNums(x,y){
var t = x + y;

<input type="button" value="click" onClick="addNums(globalNumber,3)"/>

I can use a global variable in the onClick event part, I can't seem to use a variable stored in a function. I've tried returning the variable and writing:

<input type="button" value="click" onClick="addNums(ranNum(globalNumber),3)"/>

That seems like the obvious way, but it won't work for me. Thanks anyway.

Edit: It's working when I feed the onClick ranNum(),3, but not when I supply the functions variable name. Is there a reason for this?

Old Pedant
03-23-2012, 09:15 PM
I can use a global variable in the onClick event part, I can't seem to use a variable stored in a function

Variables aren't "stored" in functions. As soon as a function ends, all variable that it declared (using the var keyword) disappear.

It's called "variable scope", and it's pretty much universal across all computer languages. (Some languages add more scopes, but I can think of any language that declares variables local to a function and then allows them to be accessed outside the function. Okay, except by nested functions, but that's inapplicable here.)

03-23-2012, 09:35 PM
I see. I was just confused as to why ranNum() would work to give me the variable I was after (the one I returned to it), whereas ranNum(globalNumber) wouldn't.


Old Pedant
03-23-2012, 10:02 PM
ranNum(globalNumber) would simply ignore the globalNumber variable if it really is a global.

But if it was local to the ranNum( ) function, then it wouldn't exist outside the function, and trying to use it would give an error.

Remember, the *CALL* to the function is *NOT* part of the function. It is outside the function.

03-23-2012, 10:09 PM
Thanks, that clears it up.

03-25-2012, 06:08 PM
I've noticed that when I pass variables in this way, I'm also running the function from the place I'm passing it to.

If I make a function that generates a random number, then pass this to a second function to alert the number - it works fine.

However, if in the first function, I have something like an alert- this will happen once I call my second function. I don't want any other elements of my first function; just the returned value.

Does that make sense?

Old Pedant
03-25-2012, 09:38 PM
No. I don't understand the point at all.

Show a code example?

03-25-2012, 09:47 PM
Alright, I'm making a hangman game. I have one button to start the game (using function makeBoxes(), and another which the user will click after entering a letter to guess, checkLetter(). checkLetter will search for a match in the string of the originally generated word.

Anyway. I click first button, and I get a random word from the array and place each letter in a box. Working as intended.

When I click my second button, for now, I simply want to receive the word. It seems it's running the function again though; and giving me a different word. Not intended.


wordArray = new Array("carrot","elephant","motorcycle","rain","yellow","machine","computer","keyboard","house","planet","giraffe");

function ranNum(){
var ranNum = Math.round(Math.random()*10);
var chosenWord = wordArray[ranNum];
return chosenWord;

function makeBoxes(x){
//remove children when new word is chosen
var hM = document.getElementById("hangMan");

var chosenWord = ranNum(x);
var wL = chosenWord.length;

//create box for length of letters in word
var i = 0;
var cBoxes = document.createElement("div");
cBoxes.className = "letterBoxes";
cBoxes.innerHTML = chosenWord.charAt(i);
return chosenWord;

function checkLetter(y){
var x = makeBoxes(y);

Edit: Basically, I want to retrieve ONLY a variable(in this case, a word) from one function, I don't want any other part of the function to run or anything else to happen. I just want to grab the returned word.

03-26-2012, 12:32 AM
Lots of errors!!

chosenWord; is wrong.
If you wanna declare a variable, without assigning a value to it you must use var

var chosenWord;

var ranNum = Math.round(Math.random()*10);
is uneven:
0 and 11 would have less chance to be the result than the other numbers.
And by hardcoding the multiplier you have to change it every time you add a word to wordArray.

var ranNum = Math.floor(Math.random()*wordArray.length);
and you are also complicating it.

function ranNum(Size){
return Math.floor(Math.random()*Size)
will give an even chance for all the numbers within the chosen range Size.

chosenword = wordArray[ranNum(wordArray.length)]; will then give an equal chance for all the words to be assigned to chosenWord
function checkLetter(y){
var x = makeBoxes(y);
} you are asking it to select a new word every time you run checkLetter

using var inside a function will create a local version of the variable, which is independent from the global variable and will leave the global variable unmodified. This local variable will not be accessible outside the function.

if you have declared a variable you can modify it by any call, inside or outside a function, by:

variable = assignment

Old Pedant
03-26-2012, 03:18 AM
You also clearly don't understand the point of parameters to functions.

You invoke your ranNum function thus:

var chosenWord = ranNum(x);

supposedly passing in a value (whatever the value of variable x is).

But you declare the function itself

function ranNum(){
so that it does *NOT* take an argument.

MAKE UP YOUR MIND. Don't pass arguments if the function doesn't use them. Don't declare them in the function (as you did with function makeBoxes(x) if you aren't going to pass them.

03-26-2012, 09:40 AM
Thanks lerura. I'm aware of using the word array length instead of the set number, just didn't use it in the example provided. The function that uses size is really helpful though, thanks.

And btw: you are implying that I need to make chosenWord global so it doesn't change each time - is this the best solution? I had it working like this previously but thought there would be a better way.

And Old Pedant, I don't really know what I'm doing, you're right. That's why I'm posting for help. The whole passing parameters/ arguments/ variables thing is just confusing to me.

03-26-2012, 11:26 AM
<link rel="stylesheet" type="text/css" href="hmstyle.css"/>
<script type="text/javascript">

function random_number(){
var ran = Math.floor(Math.random()*10);
return ran;

function show_num(x){

function multiply(){
//use ran variable here ------
//I cannot access that variable
//unless I make it a global variable

//if I use random_number(ran) to grab the variable,
//it runs the function again and I receive a DIFFERENT
//random number, not the one I originally want after 1
//button press.

//I want my first button to give me a random number,
//then my third variable to simply let me operate on that number,
//not a NEW random number.


<input type="button" value="Get Number" onClick="random_number()"/>

<input type="button" value="Use Number Again" onClick="multiply()"/>


Hi guys, sorry to keep spamming, but I wanna get my head around what I'm doing wrong.

I simply want the value returned by the original button click, I want this value to remain as it is but I want that value to be passed to my multiply function, as an example, so I can multiply it.

It works fine If I use a global, but I thought the point of 'passing variables' was to do this? I can pass it as a variable by using random_number(ran), but I get a DIFFERENT number since I'm invoking the function again.

Thanks in advance.

03-26-2012, 06:02 PM
And btw: you are implying that I need to make chosenWord global so it doesn't change each time - is this the best solution? I had it working like this previously but thought there would be a better way.

Your line:

is obviously an attempt to declare a global variable.
but it is done wrong.

if you are not assigning a value to a variable you must use var to declare it,
Whereas if you are assigning a value, the use of var is optional.

var chosenWord: declares a variable without giving it an initial value.
chosenWord = string/number/boolean/array; assigns a value to the variable.
and var chosenWord = string/number/boolean/array; declares a variable and gives it a value.
var is unnecessary when you are assigning a value, as it is then automatically declared, and can be left out

chosenWord; means "execute chosenWord"
But you cannot execute an unassigned variable.
Since you need to use chosenWord later on, you need to store it, and the best way to do it, is to make it global
When parameters that are returned from another function, e.g.

function Q(){
return P*P;
the output of Q() is discarded as soon as it is used.
Only the value of P and Z is stored, but you need to run Q() again if need to use its output later on, even if it in this case would return the same value as last time you ran it.

But your function makeBoxes() used non-constants such as Math.random() so you cannot just run it once more and expect it to return the same result again.

There is a way to do it without using a global variable:


and then there is one more problem.

var hM = document.getElementById("hangMan");
sets hM equal to the tag that have the Id "hangman".
but in:

you refer to a unknown items hangMan.
The script cannot guess that you by hangMan means: the element store in hM.

03-26-2012, 06:35 PM
Thanks for that. I'll give it a try how you have suggested.

I know another way I can shortcut since I've done in previously, post the word to an invisible textbox and get it from there. I was just trying to pass the variable (the chosen word) down to the next function though, but as you said, it constantly changes.