1

I don't really understand what's happening with the snippet below.

I would expect an error because of the Temporal Dead Zone, but it looks like const baz = '123123'; gets hoisted.

What's the reason why everything works?

class Foo {
  constructor() { 
    console.log('Foo baz is:', baz) 
  }
}

function log() {
  console.log('log baz is:', baz);
}

const baz = '123123';

log();
new Foo();
Federico klez Culloca
  • 22,898
  • 15
  • 55
  • 90
Hitmands
  • 11,304
  • 26
  • 57
  • 2
    It's a *temporal* dead zone, not a *syntactic* dead zone, so if you only access the variable (in your function call) after it was initialised you're fine. Had you called the function earlier, it still would have accessed the same "hoisted" variable in that scope, but it would have thrown the exception. – Bergi Dec 04 '17 at 13:40

2 Answers2

2

It doesn't need to be hoisted.

The functions don't try to access the variable until they are called.

You don't call them until after the constant is defined and has a value assigned to it.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
1

The const declaration is (sort-of) hoisted, so it's as if your code looked like this:

const baz; // hoisted, sort-of
class Foo {
  constructor() { 
    console.log('Foo baz is:', baz) 
  }
}

function log() {
  console.log('log baz is:', baz);
}

baz = '123123'; // not really possible because it's const

log();
new Foo();

So there's a dead zone, but nothing actually happens in the dead zone; you don't make the function calls until after the dead zone so it's all good. It's fine to mention a symbol in its dead zone in nested function contexts. The dead zone is all about actively "touching" a hoisted symbol before its actual point of declaration.

Actually, because of the "temporal dead zone" concept, it's not really meaningful to think of const and let declarations as being "hoisted" the way var declarations are. This particular example is a good illustration of how the declarations can seem to be hoisted however, as the references in the nested lexical contexts do actually work because the symbol is defined by the time the code in those functions actually runs.

Pointy
  • 371,531
  • 55
  • 528
  • 584