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.
answer, counter, numTrees
are global, however when you pass them into a function as arguments;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
(You also want
counter += 1
to actually increment the variable)