Sandeep Nayak
Sandeep Nayak

Reputation: 4757

"let" vs "var" inside a "block"

Not sure if this has been answered elsewhere. I have gone through this answer

This is my code:

var fruit = "apple";
if (true) {
  console.log(fruit); // expected "apple" 
  let fruit = "orange"; // since this is not hoisted to the top
  console.log(fruit); // "orange" as expected
}

Why can't we access the outer variable fruit inside the if block. I understand that variables declared with let are not hoisted within the block/function scope.

I get Uncaught ReferenceError: fruit is not defined error. Why so?

Although, if I change the variable name inside the if block to something else, then it works as expected. So why this conflict with same name, mainly when let fruit = "orange" is not hoisted to the top.

Upvotes: 3

Views: 152

Answers (1)

Sri
Sri

Reputation: 1336

  • Scope of the variable 'fruit' is defined within the block.
  • Please look at the reference. Your scenario is well explained under 'Temporal dead zone and errors with let' & 'Another example'

Reference - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let

Thanks Sriram

Upvotes: 2

Related Questions