Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using var in a nested function to declare a variable with the same name as a parameter of parent

Tags:

javascript

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.

like image 813
Ryan Li Avatar asked Apr 05 '11 08:04

Ryan Li


1 Answers

Javascript uses function-scope, meaning that variables' scope is not like C's block-scope coming into and out of scope according to {}, but rather objects come into and out of scope by functions' beginnings and endings. As such, every local variable you define in a function is declared from the beginning of the execution of that function, and will be of type undefined until you initialise it in your function.

As such, when g executes, since it will create at some point the local variable m, the runtime already declares that there is a local m (which obviously hides the external m of the f function) with type undefined from the beginning of g's execution

See https://developer.mozilla.org/en/JavaScript/Reference/Scope_Cheatsheet which explains that when you do var varName it hoists the variable to the top of the function scope. That page has lots of great examples, here's one quote that sums it up:

Every definition of a variable is really a declaration of the variable at the top of its scope and an assignment at the place where the definition is.

like image 98
davin Avatar answered Sep 19 '22 11:09

davin