Our Javascript Code:
Key Concept:
➡ var is Function-scoped, not Block-scoped
That means:
varignores blocks like{}unless they are inside a function.- So if you declare
var xinside 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
xis created in the global scope, and its value is10.
🔸 Step 2: Enter the block
-
You’re declaring
var xagain, butvardoes not create a new variable inside the block. - Instead, it reuses the global
x. - So this overwrites
xfrom10 → 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
xwas 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:
varignores blocks, it's function-scoped, not block-scoped.- Use
letorconstif you want variables to be truly contained inside blocks.
