I have a minor problem with a JavaScript snippet that I hope you can help me solving it.
var z=0;
function xyz() {
if (!z) {
z+=5;
var h=15; // The problem resides here
}
else {
var f=h+7;
alert(f);
}
z++;
return z;
}
When I registered this function to a click event handler on a button element, I was expecting to see by the second iteration of function execution an alert message displaying
22
What I had was a NaN message indicating that the variable h wasn't defined despite the explicit declaration statement within the if branch but when I omitted the var keyword, suddenly the function behaved :)
It's really puzzling for me as I am pretty sure that JS doesn't natively support block scoping except when using the let keyword introduced by Mozilla browsers. I am also darn sure that declaring variables using the var keyword creates local scope for them and therefore they become exclusively accessible within the function in which they are defined.
So, why on the world I have to declare h as a global variable for the function to work?
Any help would be very appreciated as I am new to Web Design and I am coming from graphic design background.
Note: Actually,this was not the real life problem that I faced during coding. I was trying to create a ticker that updates every 10 seconds automatically using the setInterval() method and then suppressing it when the user browses the headlines manually and when he's done, the script takes over once again.
I thought that a more generic and simple example is more suitable to explain the solution without getting into the details of the methods/properties used.
=======
UPDATE
I think I got it now. Functions don't have memories and thus can't remember values generated from previous calls. What I was doing actually is storing the value generated from the first call in a global variable that can be accessed in future calls. But I'm wondering is there any elegant way to achieve the same result other than using global variables?