Compare the apparent hoisting behavior between these two snippets to see why the JS scoping/hoisting quiz I posted surprises me.
-
-
Save getify/11345023 to your computer and use it in GitHub Desktop.
ilustrating the diff in hoisting behavior that surprises me
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var a = 2; | |
a(); // TypeError | |
function a() { | |
console.log("yay"); | |
} | |
// ********************** | |
// Hoists as: | |
function a() { | |
console.log("yay"); | |
} | |
var a; | |
a = 2; | |
a(); // TypeError |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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