Reputation: 4757
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
Reputation: 1336
Reference - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let
Thanks Sriram
Upvotes: 2