Return and re-declare a variable from function

2.1k Views Asked by At

Working on an assignment for my Intro Programming class, I created a function and got everything working with a little help from some guys on here (thanks a ton btw) and now I have a new issue. I have two variables that I declare and prompted for a value before starting my function and causing it to prompt for a new value if it doesn't pass. But now when I return them it doesn't change the variable outside of the code.

// 1 Declare Variables
var numTrees;
var counter = 0;
var answer = "no";

function treeFunction(answer, counter, numTrees) {
while (answer == "no" && counter < 3)
{
    if (numTrees < 5 || numTrees > 10)
    {
        alert("That is an incorrect value.\nThe sample size should be less than 5 or greater than 10.\nPlease try again.");
        answer = "no";
        numTrees = prompt("Please reenter the amount of trees in your sample.");
        alert("You have entered: " + numTrees)
        counter + 1;
    }
    else 
    {
        answer = "yes";
    }
}
if (answer == "no") {
    alert("You have entered an incorrect number too many times.\nThe Program will now end.");
    window.open('', '_self', '');
    window.close();
} else if (answer == "yes") {
    return numTrees;
}
}
// 2 Prompt the Instructor for the number of Trees
numTrees = prompt("How many trees are in your sample?");
alert("You have entered: " + numTrees);
treeFunction(answer, counter, numTrees)
document.write(numTrees); 
document.write("<br/>")
document.write("<br/> <br/>" + "End of Program.");

EDIT: I have change what I'm doing, I no longer need to return both variables, only numTrees. howver the document.write for some reason show the original value, not the value it was changed to in the function even after return.

3

There are 3 best solutions below

5
On BEST ANSWER

answer, counter, numTrees are global, however when you pass them into a function as arguments;

function treeFunction(answer, counter, numTrees) {

you get a set of new local variables which happen to have the same name as the globals, and therefore hide them.

To use the globals, dont pass them

function treeFunction() {
   answer = ....

(You also want counter += 1 to actually increment the variable)

1
On

instead of calling return twice (which will not work anyway), you can return an Array.

return [numTrees, answer];

So now we can catch that by assigning the return value and access it:

var ret = treeFunction(answer, counter, numTrees);

// ret[0] is "numTrees"
// ret[1] is "answer"
0
On
  1. A function can return only one value. So, return numTrees; return answer;

the second statement will not get executed.

  1. Since, variables are declared outside the function, they are global. So, you dont need to return it. ie, it will have modified value after the function completes execution.