JavaScript Closures: Understanding Lexical Scope and Variable Reassignment

🧠 Most JavaScript devs miss this subtle detail 👀 Especially those with 1–2 years of experience. No frameworks. No libraries. Just core JavaScript fundamentals. 🧩 Output-Based Question (Closures) function outer() { let x = 10; return function inner() { console.log(x); }; } const fn = outer(); x = 20; fn(); ❓ What will be printed? (Don’t run the code ❌) A. 10 B. 20 C. undefined D. Throws an error 👇 Drop your answer in the comments Why this matters This question tests: closures lexical scope how JavaScript remembers variables why reassignment doesn’t always change behavior When fundamentals aren’t clear: outputs feel confusing bugs feel random debugging turns into guesswork Good developers don’t just write code. They understand how JavaScript thinks. 💡 I’ll pin the explanation after a few answers. #JavaScript #WebDevelopment #Coding #Programming #Closures #JavaScriptFundamentals #DevCommunity #SoftwareEngineering #TechEducation #LearnToCode

  • text, letter

If we are using strict mode. Then we will get an error and if not then we get an out 10 because of clouser it means The function keeps a reference to the variable from its lexical scope, not a copy of the value.

10 because of lexical scope. inner function will read the x set within the bounds of the outer block but the x = 20 is set outside of the function so the inner function will not reach out to it, it will access the x = 10.

A) 10, due to the function keeping the reference to the variable through its lexical scoping.

it’s easy - 10🙂↔️ We are student of Akshay Saini 🚀

output will be 10. why? inner function rememebers the value of the variable created in its lexical scope...that's why output will be 10.

Definitely A if not using strict mode as suraj narule already explained it well

Best to understand Scoping in JS, 1st x = 20 doen't affect as it's global variable. Now, x=10 ans always

The answer will be 10. It is the concept of lexical scope

10 closure formation, and let is block scoped

See more comments

To view or add a comment, sign in

Explore content categories