How Hoisting Works for Functions
hoisting is a behavior where variable and function declarations are moved to the top of their containing scope (either the global scope or a function scope) during the compilation phase, before the code executes.
In JavaScript, hoisting is a behavior where variable and function declarations are moved to the top of their containing scope (either the global scope or a function scope) during the compilation phase, before the code executes. This allows you to use functions and variables before they are declared in your code. However, the actual values assigned to variables are not hoisted—only the declarations.
Function Declarations
Entire function declarations are hoisted, so you can call the function even before you declare it.
sayHello(); // Works because the function declaration is hoistedfunction sayHello() {console.log("Hello!");}
Function Expressions and Arrow Functions
Only the variable (not the function itself) is hoisted when using function expressions or arrow functions. If you try to call them before they are defined, you'll get a TypeError
because the variable is hoisted without an assigned value.
sayHi(); // TypeError: sayHi is not a functionvar sayHi = function() {console.log("Hi!");};
Key Takeaways
Only declarations are hoisted, not initializations or assignments.
var
is hoisted with a default value ofundefined
, whilelet
andconst
are hoisted but remain in the temporal dead zone.Entire function declarations are hoisted, but not function expressions or arrow functions.