This is because of the line var v = 0; by doing this you have create a local variable in the function called v so when you say v=20 you are referring to the local v not the global v.
To prove this I created this snippet to show it is the var that creates this behavior. The log function in the snippet is just there so you can view the output in the DOM.
var v = 10;
function fun() {
v = 20;
if (v > 10) {
var v = 0;
}
}
function bar() {
v = 20;
if (v > 10) {
v = 0;
}
}
log("Before fun:",v);
fun();
log("After fun:",v);
bar();
log("After bar:",v);
function log (){
document.getElementById("log").innerHTML += Array.prototype.slice.call(arguments).join(' ') + '<br>';
}
<div id="log"></div>
The best way I have found to visualize this process is the following.
var v = 10;
function fun() {
v = 20;
if (v > 10) {
var v = 0;
}
}
fun();
I convert this into the following in my mind which is the process of hoisting.
var v = 10;
function fun() {
var v;
v = 20;
if (v > 10) {
v = 0;
}
}
fun();
With this new code it is clear that v = 20 refers to the local v not the global v.