Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.