Function Hoisting
Function Hoisting
Section titled “Function Hoisting”Introduction
Section titled “Introduction”Function declarations are fully hoisted — both the name and the body are moved to the top of their scope during the creation phase.
Fully Hoisted
Section titled “Fully Hoisted”// ✅ Can call before definitionsayHello(); // 'Hello!'
function sayHello() { console.log('Hello!');}
// This works because during creation phase,// the entire function is stored in memoryNot All Function Definitions are Hoisted
Section titled “Not All Function Definitions are Hoisted”// ❌ Function expressions are NOT hoistedsayHi(); // TypeError: sayHi is not a function
var sayHi = function() { console.log('Hi!');};// var sayHi is hoisted as undefined, but the assignment doesn't happen yet
// ❌ Arrow functions are NOT hoistedgreet(); // ReferenceError: Cannot access before initialization
let greet = () => { console.log('Hello!');};// let greet is in TDZBest Practices
Section titled “Best Practices”- Declare functions before using them (even though declarations are hoisted)
- Use function declarations for top-level functions
- Use function expressions/arrows when hoisting is undesirable
Summary
Section titled “Summary”functiondeclarations are fully hoisted (name + body)- Function expressions and arrow functions are NOT hoisted
- Hoisting makes code more flexible but can be confusing
- Best practice: declare before use