JavaScript Hoisting Explained: Why a = 10; console.log(a); outputs undefined

🚀 JavaScript Tricky Question — Can you predict the output? console.log(a); var a = 10; function test() { console.log(a); var a = 20; } test(); 🧠 What will be the output? Most developers expect: 10 20 But the actual output is: undefined undefined ✅ Why does this happen? This is due to hoisting in JavaScript. var declarations are hoisted to the top But their values are not initialized immediately So the variable exists, but its value is undefined Behind the scenes, JavaScript interprets it like this: var a; console.log(a); // undefined a = 10; function test() { var a; console.log(a); // undefined a = 20; } Real-world takeaway Understanding hoisting is critical when: * Debugging unexpected undefined values * Working with legacy JavaScript code * Preparing for frontend interviews * Writing predictable, maintainable code 💡 My learning lesson: Always declare variables at the top of the scope and prefer let / const over var to avoid hoisting-related bugs. #FrontendDeveloper #JavaScript #ReactJS #WebDevelopment #FrontendInterview #Coding #SoftwareEngineering #TechLearning #hiringFrontend

Hoisting is one of those fundamentals that quietly affects real code more than expected.

To view or add a comment, sign in

Explore content categories