Understanding JavaScript Scope Chain and Lexical Environment

Most bugs in JavaScript don’t come from syntax. They come from 𝐧𝐨𝐭 𝐮𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠 𝐡𝐨𝐰 𝐬𝐜𝐨𝐩𝐞 𝐚𝐜𝐭𝐮𝐚𝐥𝐥𝐲 𝐰𝐨𝐫𝐤𝐬. Today, I went back to revise one of the most important fundamentals from Akshay Saini 🚀 #NamasteJavaScript 𝐒𝐜𝐨𝐩𝐞, 𝐋𝐞𝐱𝐢𝐜𝐚𝐥 𝐄𝐧𝐯𝐢𝐫𝐨𝐧𝐦𝐞𝐧𝐭, 𝐚𝐧𝐝 𝐭𝐡𝐞 𝐒𝐜𝐨𝐩𝐞 𝐂𝐡𝐚𝐢𝐧. Let’s understand this using the image below. When the code shown in the image is executed: 1. First, it creates the 𝐆𝐥𝐨𝐛𝐚𝐥 𝐄𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧 𝐂𝐨𝐧𝐭𝐞𝐱𝐭 (bottom box in the image) 2. When function a() is called, a 𝐧𝐞𝐰 𝐄𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧 𝐂𝐨𝐧𝐭𝐞𝐱𝐭 is pushed to the call stack 3. When function c() is called, 𝐚𝐧𝐨𝐭𝐡𝐞𝐫 𝐄𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧 𝐂𝐨𝐧𝐭𝐞𝐱𝐭 is created on top As, I already posted in my previous post each execution context has 𝐭𝐰𝐨 𝐩𝐚𝐫𝐭𝐬: • Memory • Code And 𝐞𝐚𝐜𝐡 𝐨𝐧𝐞 𝐚𝐥𝐬𝐨 𝐠𝐞𝐭𝐬 𝐚 𝐋𝐞𝐱𝐢𝐜𝐚𝐥 𝐄𝐧𝐯𝐢𝐫𝐨𝐧𝐦𝐞𝐧𝐭 — which contains: • Its local variables • And a 𝐫𝐞𝐟𝐞𝐫𝐞𝐧𝐜𝐞 𝐭𝐨 𝐢𝐭𝐬 𝐩𝐚𝐫𝐞𝐧𝐭’𝐬 𝐥𝐞𝐱𝐢𝐜𝐚𝐥 𝐞𝐧𝐯𝐢𝐫𝐨𝐧𝐦𝐞𝐧𝐭 (shown by arrows in the image orange box's) Now comes the most important part: 𝐒𝐜𝐨𝐩𝐞 𝐂𝐡𝐚𝐢𝐧 When c() tries to access a variable: • It first looks in 𝐢𝐭𝐬 𝐨𝐰𝐧 𝐦𝐞𝐦𝐨𝐫𝐲 • If not found → it follows the 𝐚𝐫𝐫𝐨𝐰 𝐭𝐨 𝐩𝐚𝐫𝐞𝐧𝐭 (𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐚) • If still not found → it goes to 𝐆𝐥𝐨𝐛𝐚𝐥 • If still not found → ❌ ReferenceError This 𝐩𝐚𝐭𝐡 𝐨𝐟 𝐚𝐫𝐫𝐨𝐰𝐬 is called the Scope Chain. So in this diagram: • c() does not find the variable in its own memory • It goes one level up to a( ) memory • Finds it there • And executes successfully But when we try to access the same variable from 𝐠𝐥𝐨𝐛𝐚𝐥, there is 𝐧𝐨 𝐩𝐚𝐭𝐡 𝐮𝐩𝐰𝐚𝐫𝐝 — so JavaScript throws an error. It matters where the function is written, not where it is called. That’s why it’s called 𝐋𝐞𝐱𝐢𝐜𝐚𝐥 𝐒𝐜𝐨𝐩𝐞. 𝐒𝐜𝐨𝐩𝐞 𝐢𝐬 𝐟𝐢𝐱𝐞𝐝 𝐚𝐭 𝐰𝐫𝐢𝐭𝐞 𝐭𝐢𝐦𝐞, 𝐧𝐨𝐭 𝐚𝐭 𝐫𝐮𝐧 𝐭𝐢𝐦𝐞. If you truly understand this diagram: * Closures become easy * Hoisting becomes logical * Async code becomes less “magical” * Debugging becomes 10x clearer Going back to fundamentals again and again is 𝐧𝐨𝐭 𝐚 𝐰𝐚𝐬𝐭𝐞 𝐨𝐟 𝐭𝐢𝐦𝐞. It’s what 𝐬𝐞𝐩𝐚𝐫𝐚𝐭𝐞𝐬 𝐫𝐞𝐚𝐥 𝐞𝐧𝐠𝐢𝐧𝐞𝐞𝐫𝐬 𝐟𝐫𝐨𝐦 𝐭𝐮𝐭𝐨𝐫𝐢𝐚𝐥 𝐜𝐨𝐝𝐞𝐫𝐬. Huge credit to Akshay Saini 🚀and the #NamasteJavaScript series  for creating such a strong foundation in JavaScript internals. If you write JavaScript and 𝐜𝐚𝐧’𝐭 𝐝𝐫𝐚𝐰 𝐭𝐡𝐢𝐬 𝐝𝐢𝐚𝐠𝐫𝐚𝐦 𝐟𝐫𝐨𝐦 𝐦𝐞𝐦𝐨𝐫𝐲 — you’ve found your next revision topic. Back to basics. Always..🚀 Source: Namaste JavaScript – Scope Chain & Lexical Environment [https://lnkd.in/g5h-dA2P) #JavaScript #NamasteJavaScript #AkshaySaini #SoftwareEngineering #WebDevelopment #LearningInPublic #Backend #nodejs #systemdesign #Developers

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories