Our Javascript Code:
Key Concept:
➡ var
is Function-scoped, not Block-scoped
That means:
var
ignores blocks like{}
unless they are inside a function.- So if you declare
var x
inside a block, it’s actually the same variable as outside the block!
Step-by-Step Execution
🔸 Step 1: Declare x
in the global scope
- A variable
x
is created in the global scope, and its value is10
.
🔸 Step 2: Enter the block
-
You’re declaring
var x
again, butvar
does not create a new variable inside the block. - Instead, it reuses the global
x
. - So this overwrites
x
from10 → 20
.
First console.log(x)
:
- At this point,
x = 20
.
🔸 Step 3: Exit the block
You're back in the global scope.
Second console.log(x)
:
- Since
x
was overwritten inside the block (which affected the samex
), it's still20
.
✔ Final Answer:
C) 20 20
This question appeared in the Infosys 1st round of interview, testing the candidate’s knowledge of functional scope and block scope when we declare a variable using var keyword in JavaScript.
Remember key Takeaway:
var
ignores blocks, it's function-scoped, not block-scoped.- Use
let
orconst
if you want variables to be truly contained inside blocks.