Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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.

like image 734
Sandeep Nayak Avatar asked Mar 11 '26 20:03

Sandeep Nayak


1 Answers

  • 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

like image 118
Sri Avatar answered Mar 14 '26 10:03

Sri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!