Skip to content

Instantly share code, notes, and snippets.

@thomheymann
Created October 5, 2015 16:50
Show Gist options
  • Save thomheymann/36603fbc20de8e04fd09 to your computer and use it in GitHub Desktop.
Save thomheymann/36603fbc20de8e04fd09 to your computer and use it in GitHub Desktop.
Variable vs. function hoisting
// 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'; };
})();
// 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'
})();
// 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