hoisting
What is hoisting
Hoisting is a JavaScript mechanism in which variable and function declarations are "moved" to the top of the scope (before the code executes).
But it's important: only declarations are hoisted, not value assignments.
1. Function Declaration - can be called before declaration
javascript
sayHi(); // Works!
function sayHi() {
console.log("Hello!");
}Why it works:
- During the preparation phase, the interpreter finds
function sayHiand creates the function in advance in memory. - When the code executes line by line, the function is already available.
Result:
javascript
Hello!2. Function Expression - does not work
javascript
sayHi(); // TypeError: sayHi is not a function
const sayHi = function() {
console.log("Hello!");
};Why it does not work:
const sayHiis hoisted (hoisting exists), but only the variable declaration itself, without assigning the function.- Before the initialization line,
sayHiis in the "temporal dead zone" (TDZ). - Accessing it before assignment causes an error.
3. Arrow Function - the same thing
javascript
greet(); // TypeError: greet is not a function
const greet = () => console.log("Hello!");Why:
- Arrow functions are function expressions, just with different syntax.
- So the behavior is the same: the variable is unavailable until it is assigned.
4. var + function expression - a special case
javascript
sayHi(); // TypeError: sayHi is not a function
var sayHi = function() {
console.log("Hello!");
};What happens:
- The variable
sayHiis hoisted (hoisting withvar), but it is assigned the valueundefinedbefore the line with the function executes. - At the moment of calling
sayHi(), it isundefined, not a function, so it errors.
Quick summary
| Declaration method | Can it be called before declaration? | Why |
|---|---|---|
function declaration | Yes | The function is fully "hoisted" |
function expression (const/let) | No | The variable is in the TDZ |
function expression (var) | No | The variable is undefined before assignment |
arrow function | No | Same as function expression |
Visualizing hoisting
javascript
// Roughly what happens inside the JavaScript engine:
function sayHi() { console.log("Hello!"); } // fully hoisted
var sayBye; // hoisted, but without a value
sayHi(); // works
sayBye(); // error (undefined)
sayBye = function() { console.log("Bye!"); };Summary
Function Declaration functions are created in advance and available in the whole scope. Function Expression and Arrow Function are not - they can only be called after declaration.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.