Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    New Coder
    Join Date
    Nov 2011
    Posts
    28
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Best way to retrieve variable from one function and use it in another

    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:

    Code:
    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;
        alert(total);
    }
    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.
    Last edited by pixo_newb; 03-23-2012 at 04:20 PM.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,695
    Thanks
    80
    Thanked 4,511 Times in 4,475 Posts
    It is the best way.

    Leave it alone.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    pixo_newb (03-23-2012)

  • #3
    New Coder
    Join Date
    Nov 2011
    Posts
    28
    Thanks
    13
    Thanked 0 Times in 0 Posts
    Thanks mate.
    Another quick question.

    Code:
    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;
    	alert(t);
    }
    
    ----
    <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:

    Code:
    <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?
    Last edited by pixo_newb; 03-23-2012 at 07:54 PM.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,695
    Thanks
    80
    Thanked 4,511 Times in 4,475 Posts
    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.)
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    pixo_newb (03-23-2012)

  • #5
    New Coder
    Join Date
    Nov 2011
    Posts
    28
    Thanks
    13
    Thanked 0 Times in 0 Posts
    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.

    Thanks.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,695
    Thanks
    80
    Thanked 4,511 Times in 4,475 Posts
    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.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    pixo_newb (03-23-2012)

  • #7
    New Coder
    Join Date
    Nov 2011
    Posts
    28
    Thanks
    13
    Thanked 0 Times in 0 Posts
    Thanks, that clears it up.

  • #8
    New Coder
    Join Date
    Nov 2011
    Posts
    28
    Thanks
    13
    Thanked 0 Times in 0 Posts
    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.

    Ie:
    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?

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,695
    Thanks
    80
    Thanked 4,511 Times in 4,475 Posts
    No. I don't understand the point at all.

    Show a code example?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    pixo_newb (03-25-2012)

  • #10
    New Coder
    Join Date
    Nov 2011
    Posts
    28
    Thanks
    13
    Thanked 0 Times in 0 Posts
    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.

    Here:
    Code:
    wordArray = new Array("carrot","elephant","motorcycle","rain","yellow","machine","computer","keyboard","house","planet","giraffe");
    chosenWord;
    
    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");
    	while(hM.firstChild){
    		hM.removeChild(hM.firstChild);
    	}	
    	
    	var chosenWord = ranNum(x);
    		var wL = chosenWord.length;
    
    		//create box for length of letters in word
    		var i = 0;
    		for(i=0;i<wL;i++){		
    			var cBoxes = document.createElement("div");
    				cBoxes.className = "letterBoxes";
    					cBoxes.innerHTML = chosenWord.charAt(i);
    						hangMan.appendChild(cBoxes);
    				}	
    		return chosenWord;
    }
    
    function checkLetter(y){
    	var x = makeBoxes(y);
    	alert(x);
    }
    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.
    Last edited by pixo_newb; 03-25-2012 at 09:08 PM.

  • #11
    Regular Coder Lerura's Avatar
    Join Date
    Aug 2005
    Location
    Denmark
    Posts
    947
    Thanks
    0
    Thanked 130 Times in 129 Posts
    Lots of errors!!
    Code:
    chosenWord;
    is wrong.
    If you wanna declare a variable, without assigning a value to it you must use var
    Code:
    var chosenWord;
    ---------
    Code:
    	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.
    Code:
    	var ranNum = Math.floor(Math.random()*wordArray.length);
    and you are also complicating it.
    Code:
    function ranNum(Size){
    return Math.floor(Math.random()*Size)
    }
    will give an even chance for all the numbers within the chosen range Size.
    Code:
    chosenword = wordArray[ranNum(wordArray.length)];
    will then give an equal chance for all the words to be assigned to chosenWord
    ------------
    by:
    Code:
    function checkLetter(y){
    	var x = makeBoxes(y);
    	alert(x);
    }
    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:
    Code:
    variable = assignment

  • Users who have thanked Lerura for this post:

    pixo_newb (03-26-2012)

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,695
    Thanks
    80
    Thanked 4,511 Times in 4,475 Posts
    You also clearly don't understand the point of parameters to functions.

    You invoke your ranNum function thus:
    Code:
        var chosenWord = ranNum(x);
    supposedly passing in a value (whatever the value of variable x is).

    But you declare the function itself
    Code:
        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.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    pixo_newb (03-26-2012)

  • #13
    New Coder
    Join Date
    Nov 2011
    Posts
    28
    Thanks
    13
    Thanked 0 Times in 0 Posts
    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.
    Last edited by pixo_newb; 03-26-2012 at 08:59 AM.

  • #14
    New Coder
    Join Date
    Nov 2011
    Posts
    28
    Thanks
    13
    Thanked 0 Times in 0 Posts
    Code:
    <head>
    <link rel="stylesheet" type="text/css" href="hmstyle.css"/>
    <script type="text/javascript">
    
    function random_number(){
    	var ran = Math.floor(Math.random()*10);
    		show_num(ran)
    			return ran;
    }
    
    function show_num(x){
    	alert(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.
    }
    
    </script>
    </head>
    <body>
    
    <input type="button" value="Get Number" onClick="random_number()"/>
    
    <input type="button" value="Use Number Again" onClick="multiply()"/>
    
    </body>
    </html>
    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.

  • #15
    Regular Coder Lerura's Avatar
    Join Date
    Aug 2005
    Location
    Denmark
    Posts
    947
    Thanks
    0
    Thanked 130 Times in 129 Posts
    Quote Originally Posted by pixo_newb View Post
    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:
    Code:
    chosenWord;
    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.
    Code:
    P=2;
    function Q(){
    return P*P;
    }
    Z=17*Q();
    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:
    Code:
    document.getElementById('hangMan').getElementsByTagName('div')[x].innerHTML.
    and then there is one more problem.
    Code:
    var hM = document.getElementById("hangMan");
    sets hM equal to the tag that have the Id "hangman".
    but in:
    Code:
    hangMan.appendChild(cBoxes);
    you refer to a unknown items hangMan.
    The script cannot guess that you by hangMan means: the element store in hM.

  • Users who have thanked Lerura for this post:

    pixo_newb (03-26-2012)


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •