Skip to content

Instantly share code, notes, and snippets.

@Sljubura
Created February 10, 2013 15:33
Show Gist options
  • Save Sljubura/4749948 to your computer and use it in GitHub Desktop.
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.
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