In Pro JavaScript with Mootools book I have found the below line
The scoping rules for function expressions are a bit different from function
declarations because they depend on variable scoping. Remember that in
JavaScript, the var keyword defines a variable to be scoped locally, and
omitting the keyword creates a global variable instead:
As per my understanding I have written the below code and tried to check this
var a = function(){
b = function(){ c = function(){ alert("b"); }; };
};
alert(typeof a); // Returned me 'function'
alert(typeof b); // Returned me 'undefined'
alert(typeof c); // Returned me 'undefined'
And I also tried below
var a = function(){
var b = function(){ c = function(){ alert("b"); }; };
};
alert(typeof a); // Returned me 'function'
alert(typeof b); // Returned me 'undefined'
alert(typeof c); // Returned me 'undefined'
Could you please explain this to make me understand better. As per my understanding in first block of code b and c should be global variables.. But this is not happening in this case. Even I tried to invoke a()
before alerts... Here is the fiddle. Please help me on this to understand scope better.
They are, but they won't have values assigned to them until
a
is called (and untilb
is called in the case ofc
).That code is different. You have
var b
, which makesb
a local variable and not a global.Google the key word below, it is a good place to master scoping and other javascript pattern techniques. It is a series of articles with 12 parts. There are no direct links on the website so you need search for the rest of the articles using part number