Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Last active August 29, 2015 14:14
Show Gist options
  • Save mxriverlynn/2a2ec5f4db66bc70fcc4 to your computer and use it in GitHub Desktop.
Save mxriverlynn/2a2ec5f4db66bc70fcc4 to your computer and use it in GitHub Desktop.
explained
// #javascript if not for closures, this should blow up
var f = function(){
if (true) {var v1= 1;}
if(true) {var v2 =2;}
return v1+v2;
}
console.log(f());
function f(){
var v1, v2;
if (true){
v1 = 1;
}
if (true){
v2 = 2;
}
return v1+v2;
}

its' not closures that allow this to work. it is a combination of function scoped variables, and variable hoisting.

Variable Scope

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.

Variable Hoisting

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.

Rewriting The Function

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;
}
function f(){
if (true){
let v1 = 1;
}
if (true){
let v2 = 2;
}
// this throws an error
// because the variables are scopes
// and not available outside the if blocks
return v1+v2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment