Created
October 5, 2015 16:50
-
-
Save thomheymann/36603fbc20de8e04fd09 to your computer and use it in GitHub Desktop.
Variable vs. function hoisting
This file contains 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
// Both, function declaration and function body are hoisted to top of scope. | |
// Outside of scope, hence ReferenceError | |
console.log(foo); // ReferenceError: foo is not defined | |
(function () { | |
// Declaration and function body got hoisted to top of scope | |
console.log(foo); // [Function: foo] | |
console.log(foo()); // 'bar' | |
function foo() { return 'bar'; }; | |
})(); |
This file contains 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
// Variable declarations are hoisted to top of scope. | |
// Variable assignments are not. | |
// Outside of scope, hence ReferenceError | |
console.log(foo); // ReferenceError: foo is not defined | |
(function () { | |
// Variable declaration got hoisted to top of scope, but the variable assignment did not, hence undefined | |
console.log(foo); // undefined | |
var foo = 'bar'; | |
// After variable assignment | |
console.log(foo); // 'bar' | |
})(); |
This file contains 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
// Assigning a variable with a function is exactly the same | |
// Outside of scope, hence ReferenceError | |
console.log(foo); // ReferenceError: foo is not defined | |
(function () { | |
// Variable declaration got hoisted to top of scope, but the variable assignment did not, hence undefined | |
console.log(foo); // undefined | |
// Attempting to call undefined at this point will produce a TypeError | |
foo(); // TypeError: undefined is not a function | |
var foo = function () { return 'bar'; }; | |
// After variable assignment | |
console.log(foo); // [Function: foo] | |
console.log(foo()); // 'bar' | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment