JavaScript Hoisting: Function Declarations vs Var Declarations

Why does foo() sometimes log "B" and other times "A"? Understanding JavaScript Hoisting with var and Function Declarations 🚀 If you've ever encountered this code snippet and wondered why the first call logs "B" and the later call logs "A", you’re not alone: What’s going on here? At first glance, one might expect foo to be undefined before the variable assignment line, because of var foo, causing foo() to throw an error on the first call. But JavaScript behaves a bit differently. Here’s why: Key points about hoisting: 1️⃣ Function declarations are fully hoisted — their binding and body are available before execution starts. 2️⃣ Variable declarations (var) are hoisted too but only their names — NOT their assignments. 3️⃣ If a function declaration and a variable declaration share the same name, the function declaration takes priority during hoisting. How execution unfolds step-by-step: The function foo that logs "B" is hoisted — so at runtime, before any code executes, foo points to this function. The variable declaration var foo; is also hoisted, but does not overwrite the function at this stage. When foo(); executes the first time, it calls the hoisted function and logs "B". Then the assignment foo = function() { console.log("A") } runs, overwriting the original function. The second foo(); call then logs "A". Why doesn’t var foo reset foo to undefined before assignment? Because hoisting only lifts the declaration name, not the initialization. The function declaration’s initialization happens before variable declarations. Only when the interpreter reaches the line with the assignment, does foo get assigned the new function expression — and that replaces the original function. Function declarations hoist their definitions first — foo exists as a function at the start. var declarations hoist the variable name but do not initialize it until runtime. The assignment to foo happens in order and overwrites the hoisted function later. Understanding these nuances helps avoid confusions and tricky bugs! Remember: hoisting is about declarations only, not assignments. If this cleared up a mystery for you, or if you have other JavaScript hoisting quirks you want to discuss, drop a comment below! 👇✨ #JavaScript #WebDevelopment #CodingTips #Programming #JavaScriptTips #Hoisting #CodeUnderstanding

  • text

💯 Great breakdown!JS hoisting trips up even experienced devs — and this example perfectly shows how function declarations and var behave very differently 🧠⚡ 🟦 Function declarations → fully hoisted🟧 var → name only hoisted➡️ Function wins first, assignment overrides later Super clear explanation — love how you walked through it step‑by‑step! 🙌✨

To view or add a comment, sign in

Explore content categories