It seemed to me, that I have understood the basic concepts of JavaScript scoping and hoisting. This question+answer helped me a lot, in that regard.
Though, recently I've come across something, that surprised me a bit. Consider the following code:
var a = 1;
if (true) {
  console.log(a);
  let a = 2;
}
console.log(a);
Given of what I have learned, I would expect it to output undefined and 1. Though it results in Uncaught ReferenceError: a is not defined.
My understanding is, that code above should be equivalent to (as declaration part of let a = 2; should be hoisted to the nearest inclosing block — which is if, in this case):
var a = 1;
if (true) {
  let a;
  console.log(a);
  a = 2;
}
console.log(a);
And this code, by the way, produces undefined and 1, as I would expect.
My question is:
- Are variables declared with lethoisted, inside their nearest enclosing block?- If yes, why the code from the first block results in Uncaught ReferenceError: a is not defined?
 
- If yes, why the code from the first block results in