its' not closures that allow this to work. it is a combination of function scoped variables, and variable hoisting.
javascript only has 2 scopes for variables, in version ES5: function and global. by using a var
statement inside of a function, you are using a function-scoped variable.
In a browser, if you omit the var
statement, or if you use var
outside of any function, you will attach to the current global scope.
In a nodejs module / file, a variable declared outside of a function will be scoped to the module / file, because CommonJS modules are all wrapped in their own sandbox (function scope). You have to be more explicit to create a global variable in nodejs, and it is recommended you don't do this.
when you declare a variable inside of a function, the variable declaration is "hoisted" to the top of the function. That is, the declaration actually happens at the beginning of the function, in spite of where you put the var
statement.
Because of this hoisting, it is recommended that you put variable declarations at the top of the function. It will happen for you, anyways, so you may as well do this explicitly in order to prevent confusion about the code's execution.
Here is the equivalent function, making the implicit hoisting in to explicit variable declarations:
function f(){
var v1, v2;
if (true){
v1 = 1;
}
if (true){
v2 = 2;
}
return v1+v2;
}