JavaScript Scope Chain Explained

A lot of freshers say: 👉 var is global scope 𝗕𝘂𝘁 𝘁𝗵𝗮𝘁’𝘀 𝗻𝗼𝘁 𝗳𝘂𝗹𝗹𝘆 𝗰𝗼𝗿𝗿𝗲𝗰𝘁. var → global + function scope (❌ does NOT respect block) let / const → global + function + block scope (✅ respect block) Example: if (true) {  var a = 10;  let b = 20;  const c = 30; } console.log(a); // 10 console.log(b); // Error console.log(c); // Error 👉 var comes outside because it ignores block scope 👉 let and const stay inside the block 🔹 𝗢𝗻𝗲 𝗶𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 👇 If var is declared globally, it attaches to window (in browser): var x = 10; console.log(window.x); // 10 But let and const don’t: let y = 20; const z = 30; console.log(window.y); // undefined console.log(window.z); // undefined 👉 𝗧𝗵𝗮𝘁’𝘀 𝘄𝗵𝘆 𝗽𝗲𝗼𝗽𝗹𝗲 𝘁𝗵𝗶𝗻𝗸 𝘃𝗮𝗿 𝗶𝘀 𝗮𝗹𝘄𝗮𝘆𝘀 𝗴𝗹𝗼𝗯𝗮𝗹 🔹 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗦𝗰𝗼𝗽𝗲 𝗖𝗵𝗮𝗶𝗻? It’s just how JavaScript finds variables. It looks step by step: 𝗰𝘂𝗿𝗿𝗲𝗻𝘁 𝘀𝗰𝗼𝗽𝗲 → 𝗼𝘂𝘁𝗲𝗿 𝘀𝗰𝗼𝗽𝗲 → 𝗴𝗹𝗼𝗯𝗮𝗹 𝘀𝗰𝗼𝗽𝗲 const globalVar = "Global"; function outer() {  const outerVar = "Outer";  function inner() {   console.log(outerVar);  // outer scope   console.log(globalVar); // global scope  }  inner(); } 👉 JS first checks inside inner() 👉 then goes to outer() 👉 then global This process is called scope chain. Once you get this, closures and many JS concepts start making sense. Please follow Mohit Sharma for more😉 #JavaScript #FrontendDevelopment #Coding #WebDevelopment #JSConcepts

To view or add a comment, sign in

Explore content categories