**Hoisting** is JavaScript's behavior of moving declarations to the top of their scope during the creation phase. **var** declarations are hoisted and initialized to `undefined`. **Function declarations** are fully hoisted (name and body). **let** and **const** are hoisted but not initialized — they're in the **Temporal Dead Zone** (TDZ).
1Understanding Hoisting
Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the creation phase. var declarations are hoisted and initialized to undefined. Function declarations are fully hoisted (name and body). let and const are hoisted but not initialized — they're in the Temporal Dead Zone (TDZ).
Function declarations are fully hoisted — you can call them before they appear in code. Function expressions are NOT hoisted.
// var hoisting
console.log(myVar); // undefined (not ReferenceError!)
var myVar = 'hello';
console.log(myVar); // 'hello'
// Internally JS sees it as:
var myVar; // hoisted to top
console.log(myVar); // undefined
myVar = 'hello';2Practical Example
Here is a real-world application of Hoisting showing how it is used in production JavaScript code.
// Function declaration - fully hoisted
greet(); // works! 'Hello, World!'
function greet() {
console.log('Hello, World!');
}
// Function expression - NOT hoisted
// sayHi(); // TypeError: sayHi is not a function
const sayHi = () => 'Hi!';3Best Practices
Follow these guidelines when working with Hoisting:
1. Avoid relying on hoisting — declare before use
2. Use const/let to get TDZ protection against accidental early access
3. Understand hoisting to debug unexpected undefined values
Tip: Function declarations are fully hoisted — you can call them before they appear in code. Function expressions are NOT hoisted.
// var hoisting
console.log(myVar); // undefined (not ReferenceError!)
var myVar = 'hello';
console.log(myVar); // 'hello'
// Internally JS sees it as:
var myVar; // hoisted to top
console.log(myVar); // undefined
myVar = 'hello';