How are the variables scoped, initialized and used outside and inside javascript functions? I have written following code:
<div id="output">
</div>
<script>
var calculator = function()
{
var x = 5;
getx = function(){
return x;
}
return { x:x, getx };
}();
document.getElementById("output").innerHTML = calculator.x;
calculator.x=10;
document.getElementById("output").innerHTML += " "+ calculator.x + " "+calculator.getx();
</script>
I read that in JS execution, code is first scanned for all the variables declaration and then functions are executed.
var x defined inside calculator object is value type as its integer.
getx being nested function and as per closure will have access to variable "x" even after return of getx is executed.
First output for calculator.x is as expected=5;
Second output for calculator.x is as expected=10;
(as x is modified)
Third output for calculator.getx()
is =5; (I am not able to understand this)
"x" being value type, it should have modified value inside function scope too and third output should be=10. What am I missing here?