Rahul R Jain’s Post

🚀 The JavaScript “Gotcha” That Confuses Even Experienced Devs 😅 Let’s look at this classic head-scratcher 👇 var x = 1; function test() { console.log(x); // 🤔 What prints here? var x = 2; } test(); // Output? Most people expect 1, but the actual output is undefined ⚡ 💡 Why? When JavaScript executes this code, it doesn’t run top-to-bottom linearly. It first creates an execution context for test(). During that setup phase: The declaration var x inside test() is hoisted to the top. It’s initialized with the value undefined. This local x shadows the global one — even before assignment happens. So when console.log(x) runs, JS finds a local x (which is still undefined) and stops there. The global x = 1 is ignored completely. Now, let’s tweak one small line 👇 var x = 1; function test() { console.log(x); // No local var } test(); // ✅ Output → 1 Here, there’s no local declaration, so JS walks up the scope chain and uses the global x. 🧠 Key Takeaway In JavaScript: > “What matters is where a variable is declared, not where it’s called.” Hoisting + scope can easily cause unexpected undefined values — especially in legacy var code. ⚡ Pro Tip Prefer let or const — they’re block-scoped and avoid this trap entirely 👇 let x = 1; function test() { console.log(x); // ReferenceError ❌ (due to Temporal Dead Zone) let x = 2; } The TDZ ensures you don’t accidentally use variables before they’re initialized. 💬 Have you ever lost time debugging a “weird undefined”? Share your favorite JavaScript scope/hoisting gotcha below 👇 👉 Follow Rahul R Jain for daily deep dives into how JavaScript really works under the hood. #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #AsyncJS #Hoisting #Scope #InterviewPreparation #TechEducation #LearnToCode #WebEngineer #CodeNewbie #RahulJain

To view or add a comment, sign in

Explore content categories