Skip to content

Instantly share code, notes, and snippets.

@getify
Last active August 29, 2015 14:00
Show Gist options
  • Save getify/11345023 to your computer and use it in GitHub Desktop.
Save getify/11345023 to your computer and use it in GitHub Desktop.
ilustrating the diff in hoisting behavior that surprises me

Compare the apparent hoisting behavior between these two snippets to see why the JS scoping/hoisting quiz I posted surprises me.

var a = 2;
a(); // TypeError
function a() {
console.log("yay");
}
// **********************
// Hoists as:
function a() {
console.log("yay");
}
var a;
a = 2;
a(); // TypeError
(function(a) {
a(); // yay
function a() {
console.log("yay");
}
})(2);
// **********************
// Contents of the IIFE sorta "hoists" as:
var a;
a = 2;
function a() {
console.log("yay");
}
a(); // yay
// For further color on this, consider:
(function(a){
var a;
console.log(a);
})(2); // 2
// There, clearly, the `a` param and the `var a` local variable behave
// hoisting wise as if they're in the same scope and the `var a` is
// redundant and skipped.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment