JavaScript Hoisting and Execution Context Explained Clearly with Visual Flow, Scope Chain, and Common Pitfalls

JavaScript Hoisting and Execution Context Explained Clearly with Visual Flow, Scope Chain, and Common Pitfalls



1️⃣ What is Hoisting in JavaScript?

Hoisting is JavaScript's default behavior of moving declarations to the top of their scope during compilation.

  • Variable and function declarations are hoisted.

  • Initializations are not hoisted.


console.log(a); // undefined
var a = 10; foo(); // "Hi!" function foo() { console.log("Hi!"); }

Function declarations are hoisted with their definitions, while variables are hoisted without initialization.

 

2️⃣ Execution Context: The Hidden Engine Behind JS Code

When JavaScript runs, it creates an execution context, which consists of:

  • Memory Creation Phase (Creation phase)

    • Variable declarations are hoisted and initialized to undefined.

    • Function declarations are hoisted with body.

  • Execution Phase

    • Code runs line-by-line, assigning values and executing functions.

var x = 5;

function test() {

  console.log(x); // undefined (x is hoisted inside test)

  var x = 10;

}

test();


3️⃣ Variable Hoisting: var, let, and const Behavior

  • var is hoisted and initialized as undefined

  • let and const are hoisted but stay in Temporal Dead Zone (TDZ) until declared


console.log(a); // undefined
var a = 5; console.log(b); // ReferenceError let b = 10;

Use let and const to avoid unpredictable hoisting bugs.


 

4️⃣ Function Hoisting: Declarations vs Expressions


greet(); // Works
function greet() { console.log("Hello!"); } sayHi(); // TypeError: sayHi is not a function var sayHi = function () { console.log("Hi!"); };
  • Function declarations are hoisted completely.

  • Function expressions (assigned to var) behave like variables and are hoisted as undefined.


5️⃣ Best Practices and Common Pitfalls

✅ Use let/const instead of var
✅ Declare all variables at the top of their scope
❌ Avoid mixing declarations and logic
❌ Don’t rely on hoisting — write predictable code


// Good function start() { const name = "Techie tides"; console.log(`Welcome, ${name}`); }



"This Content Sponsored by Buymote Shopping app

BuyMote E-Shopping Application is One of the Online Shopping App

Now Available on Play Store & App Store (Buymote E-Shopping)

Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8

Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication"



Previous Post Next Post