What happens when you redeclare variable using "var" keyword, Inside a Block Scope in JavaScript? – Infosys Interview Question.


Our Javascript Code:

var x = 10;
{ var x = 20; console.log(x); } console.log(x);

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

var x = 10;

  • A variable x is created in the global scope, and its value is 10.


🔸 Step 2: Enter the block

{
var x = 20; console.log(x); }
  • You’re declaring var x again, but var does not create a new variable inside the block.
  • Instead, it reuses the global x.
  • So this overwrites x from 10 → 20.

First console.log(x):

  • At this point, x = 20.

console.log(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 same x), it's still 20.

console.log(x); // 20

✔ 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 or const if you want variables to be truly contained inside blocks.

Post a Comment

Previous Post Next Post