Do conditional statements introduce block scope for variables in JavaScript?
<p>I have a minor problem with a JavaScript snippet that I hope you can help me solving it.</p>

<pre><code>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;    
}
</code></pre>

<p>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 </p>

<pre><code>22
</code></pre>

<p>What I had was a <strong>NaN</strong> message indicating that the variable <strong>h</strong> wasn't defined despite the explicit declaration statement within the <strong>if</strong> branch but when I omitted the <strong>var</strong> keyword, suddenly the function behaved :) </p>

<p>It's really puzzling for me as I am pretty sure that JS doesn't natively support block scoping except when using the <strong>let</strong> 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. </p>

<p>So, why on the world I have to declare <strong>h</strong> as a global variable for the function to work?</p>

<p>Any help would be very appreciated as I am new to Web Design and I am coming from  graphic design background. </p>

<p>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 <strong>setInterval()</strong> method and then suppressing it when the user browses the headlines manually and when he's done, the script takes over once again. </p>

<p>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. </p>

<p>=======</p>

<h1>UPDATE</h1>

<p>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? </p>
