I'm using JavaScript to write some code and found an unexpected behaviour.
I'm using a nested function g inside f. f has a parameter named m. When using and declaring a variable inside g with the same name, something weird happens:
var f = function(m) {
var g = function() {
alert(m);
var m = 0;
};
g();
};
f(1);
This code will result in undefined, instead of 1 which I expected.
Moving the alert statement below the var line would result in the answer 0 which makes sense.
I suppose this is because JavaScript are only using functions as name closures, var m will be attached to function g with the declaration, but m is not assigned yet at the time of alert.
But I am not sure about this, because if the function is not nested, there behaviour looks nice to me:
var g = function(m) {
alert(m);
var m = 0;
};
g(1);
would produce 1.
Could anyone explain? Thank you.
undefined.undefined. I have edited the question.