What is logged?
console.log(a);
var a = 1;Options
- 1
- undefined (Correct option)
- ReferenceError
- null
Answer
undefined
Why
Before running code, JavaScript moves declarations to the top of their scope ('hoisting'). var a is hoisted and set to undefined; the assignment = 1 stays where it is.
So the code behaves like: var a; console.log(a); a = 1; → undefined.
With let or const you would get a ReferenceError: they are hoisted too, but cannot be used before their line (the 'temporal dead zone').
Remember
var is hoisted as undefined; let/const throw if used early.