Created
February 10, 2013 15:33
-
-
Save Sljubura/4749948 to your computer and use it in GitHub Desktop.
Nice example of hoisting and how local foo() function definition is pushed to the top of the scope, while the definition of bar() is not hoisted. Only its declaration.
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
function foo() { | |
console.log('global foo'); | |
} | |
function bar() { | |
console.log('global bar'); | |
} | |
function hoistMe() { | |
console.log(typeof foo); // "function" | |
console.log(typeof bar); // "undefined" | |
foo(); // "local foo" | |
bar(); // TypeError: undefined (bar) is not a function | |
// Function declaration: | |
// variable 'foo' and its implementation both get hoisted | |
function foo() { | |
console.log('local foo'); | |
} | |
// Function expression: | |
// only variable 'bar' gets hoisted, not the implementation | |
var bar = function () { | |
console.log('local bar'); | |
}; | |
} | |
hoistMe(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment