Understanding Block Scope with let in JavaScript – Asked in a Mindtree Interview


Our Javascript Code :-

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

Step-by-Step Execution

🔸 Step 1: Declare x in the global (or outer) scope

let x = 10;

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


🔸 Step 2: Enter a new block

{
let x = 20; }
  • This {} is a block.
  • Inside this block, you declare a new variable also named x using let.
  • ⚠️ This does not override the outer x! It's a completely separate variable scoped only inside the block.


🔸 Step 3: Exit the block

Now you're outside the block, so the x from inside is gone — it was block-scoped.

The only x still alive is:

let x = 10;

🔸 Step 4: console.log(x)

You are now in the outer scope, so you're accessing the outer x.

Therefore:

console.log(x); // 10

✔ Final Answer:

B) 10

This question appeared in the Mindtree 2nd round of interview, testing the candidate’s knowledge of functional scope and block scope when we declare a variable using let keyword in JavaScript.


➡ Some points about "let" keyword

  • Introduced in ES6
  • Block-scoped (unlike var, which is function-scoped)
  • Cannot be redeclared in the same scope
  • Useful for avoiding unintended overwrites

Post a Comment

Previous Post Next Post