Created
September 2, 2013 15:43
-
-
Save ivandotv/6414275 to your computer and use it in GitHub Desktop.
As you know, all variables, no matter where in the function body they are declared, get
hoisted to the top of the function behind the scenes. The same applies for functions
because they are just objects assigned to variables. The only “gotcha” is that when using
a function declaration, the definition of the function also gets hoisted, not only i…
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
/ antipattern | |
// for illustration only | |
// global functions | |
function foo() { | |
alert('global foo'); | |
} | |
function bar() { | |
alert('global bar'); | |
} | |
function hoistMe() { | |
console.log(typeof foo); // "function" | |
console.log(typeof bar); // "undefined" | |
foo(); // "local foo" | |
bar(); // TypeError: bar is not a function | |
// function declaration: | |
// variable 'foo' and its implementation both get hoisted | |
function foo() { | |
alert('local foo'); | |
} | |
// function expression: | |
// only variable 'bar' gets hoisted | |
// not the implementation | |
var bar = function () { | |
alert('local bar'); | |
}; | |
} | |
hoistMe(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment