What will be the output of following code:
const a = 1
console.log(a)
var b
console.log(b)
b = 2
console.log(c)
var c = 3
console.log(d)
let d = 2
const a = 1
No output here — just declares and initializes a
to 1
.
console.log(a)
Output: 1
Why: a
is a const
variable already initialized with the value 1
, so logging it returns 1
.
var b
No output — var
is hoisted to the top of the scope and is initialized to undefined
by default.
console.log(b)
Output: undefined
Why: b
exists because of hoisting, but since it hasn’t been assigned 2
yet, it still holds the initial undefined
.
console.log(c)
Output: undefined
Why: var c
is also hoisted and initialized to undefined
before code execution begins.
It’s not assigned 3
until the next line, so logging it here prints undefined
.
console.log(d)
Output: ❌ ReferenceError: Cannot access 'd' before initialization
Why:
let
(and const
) are hoisted but placed in the Temporal Dead Zone (TDZ) until the actual declaration line is executed.ReferenceError
instead of returning undefined
.When executed, the script prints:
1
undefined
undefined
ReferenceError: Cannot access 'd' before initialization
var
Hoisting
undefined
.undefined
.let
/ const
Hoisting + TDZ
ReferenceError
.const
Initialization Requirement
let
).Execution Order Matters