I'm setting the value of a variable inside the setAndCheck function to 1 by calling it with defined string. The value is set, but when I call the function later to check the value later, it seems like that the change has not been applied and therefore the related if statement is not executed.
The job of the function is to assign 1 to argument if called with appropriate and then it's called to check whether it's been set and return 1. If it's not then it just returns 0 at the end.
function setAndCheck(arg) {
var first_one = 0;
var second_one = 0;
if (arg == "setIt1")
first_one = 1;
else if (arg == "setIt2")
second_one = 1;
else if (arg == "checkIt1" && first_one)
return 1;
else if (arg == "checkIt2" && second_one)
return 1;
return 0;
}
I expected the output of 1 after setting both variables with "setIt1" and "setIt2". But the function still returns 0 which means the variables have the value of 0 when called with "checkIt1" or "CheckIt2".
first_oneandsecond_oneto 0 every time you call the functionvar first_one = 0is executed again as well…ifstatements - executing a function runs the entire code again. So you'd initialise a new variable calledfirst_oneand go through theifchain - on the first go you'd hit thearg == "setIt1"condition. When you execute the function again, you would initialise a new variable and hit thearg == "checkIt1" && first_onecondition which would evaluate to false, since you never went through thearg == "setIt1"condition this time;