1

I am learning JavaScript. I understood that variables created by 'let' are hoisted (as variables created by 'var') but those are not available to use until control hits the initialization statement because of temporal dead zone. If we can't use the variables, what is the need of hoisting those variables?

kadina
  • 4,024
  • 3
  • 26
  • 60
  • You're really wandering into the weeds... unless you are implementing a JavaScript compiler you likely don't need to even consider this. – Jared Smith Mar 29 '18 at 21:40
  • Thanks Jared. I just wanted to know is there any specific reason for hoisting which I am missing. – kadina Mar 29 '18 at 21:41
  • `let` and `const` are like `var` with extra rules. One of those rules is that accessing them before they're declared *throws*, which it does not with `var`. – Jared Smith Mar 29 '18 at 21:43
  • 1
    Variables declared with `let` aren't hoisted. That's what creates TDZ - gap between entering block and place where you can access the variable – Andrey Mar 29 '18 at 21:44
  • The other thing to remember is all ES5+ versions must be able to transpile back down to ES5, which might account for some of the weirdness. As Jared said, I wouldn't concern yourself too much with the behind-the-scenes implementation-- when using `let` and `const`, as far as the developer needs to be concerned they do not hoist-- they are block-scoped. Any implementation details of the underlying engine/transpilers are probably only going to be needlessly confusing, _especially_ for a beginner. – Alexander Nied Mar 29 '18 at 21:46
  • @Andrey that is incorrect. They *are* hoisted. See dave's answer for an explanation of why they have to be (i.e. shadowing). – Jared Smith Mar 29 '18 at 21:46
  • 1
    @Andery: This is interesting. The accepted answer for question https://stackoverflow.com/questions/33198849/what-is-the-temporal-dead-zone says all the variables will be hoisted and lot of websites are saying the same. – kadina Mar 29 '18 at 21:46
  • @AlexanderNied That doesn't account for any weirdness. Any language can be transpiled to ES5, whether its ES2, ES2018, Haskell, PHP, or C#. Language designers don't have to keep transpiling to other languages in mind. The transpiler's developers just need to be able to encode the rules of the language using ES5, which is usually straightforward and always possible. – Paul Mar 29 '18 at 21:57

1 Answers1

2

There is no need to hoist it, it is just something to be aware of.

If you had, as a ridiculous example:

var x = 10;

function if_x_is_10() {
    if (x === 10) {
        console.log('It was 10!');
    }
    let x = 10;
    console.log('Now it is 10!');
}

if_x_is_10();  // Uncaught ReferenceError: x is not defined

You just need to be able to realize, "oh, even though there is an x outside the function, since there is a let x inside the function, I can't access x until I am past that line, and I can't access the outer x inside of the function".

dave
  • 50,635
  • 4
  • 62
  • 77