JavaScript Quiz #002
Welcome back to day 2 of #100DaysOfQuiz! Today we peek under the hood at a classic hoisting gotcha.
Question
What will the following code print?
function foo() {
console.log(a);
var a = 1;
console.log(a);
}
foo();
Short Answer
✅ Correct choice:
undefined then 1
Deep Dive – Hoisting & the Temporal Dead Zone
-
Compile-time: JavaScript moves all
vardeclarations to the top of their function scope. Assignment stays put. So the function becomes:function foo() { var a; // ← declaration hoisted console.log(a); a = 1; // ← assignment stays console.log(a); } -
Run-time: The first
console.logsees the declared but un-initialised variable →undefined. Aftera = 1, the secondconsole.logsees the assigned value →1.
Key takeaway: only the declaration is hoisted, not the assignment.
(With let/const you’d get a ReferenceError instead—temporal dead zone!)
Try It Yourself – Tweak & Re-run
(Zero tracking, zero ads—just a sandbox.)
Share & Keep Scrolling
Got it right? Brag in the replies! Follow @learn_with_san for quiz #003 tomorrow.

0 Comments