This is an Extension to the Question. I have tried below code to understand JavaScript scope
var a = function(){
var aa = 10;
var x = 13;
b = function(){ c = function(){ alert(aa); }; };
};
a();
b();
c();
alert(typeof x); // Undefined
alert(x); // Returned me 13.
My query is I have declared variable with var inside a global function. As per my understanding x should be local. But it is not acting in that way. Someone please clear my doubt… Please check this fiddle.
The following will happen:
An alert popping up, displaying the value of
aa=10An alert popping up, saying
undefinedsince you are trying to access a variablexfrom the global scope, howeverxis only defined in the scope of function a.An error in your console,
ReferenceError: x is not defined.So, as you assume, x indeed is private, you can’t access it globally.
You probably messed something up giving you wrong results.
What might have been the case is that you forgot the var in front of the
xwhich suddenly makes it a member of the global object instead of being restricted to the function-scope. In this case, the last alert would give you 13. However the alert(typeof x) would give you"number"then.