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();

1
  • 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
    Commented Dec 4, 2017 at 13:40

2 Answers 2

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.

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.

2
  • where can I find information about this? Can you include some source?
    – Hitmands
    Commented Dec 4, 2017 at 13:37
  • 1
    The MDN documentation has some information.
    – Pointy
    Commented Dec 4, 2017 at 13:39

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.