When you modify the x=3
it is not actually changing the global variable x
but the variable declared in the function block (as var
variables have function scope). As the declaration var x
is hoisted to the top and then the modification to x = 3
happens
<script>
var x=2;
function fun(){
//var x; hoisted to the top;
console.log("x is hoisted here and uninitialized value will be", x)
x=3; //initialized, actually referring to the variable declared in the function scope
var x = 4; //declared but hoisted at the top
document.write(x);
}
document.write(x);
fun()
document.write(x);
</script>
To really change the variable at the global scope, use window.x
to refer to it:
<script>
var x=2;
function fun(){
window.x=3; //modifying the global variable 'x`
var x = 4;
document.write(x);
}
document.write(x);
fun()
document.write(x);
</script>