Javascript Temporal Dead Zone [duplicate]
Asked Answered
K

2

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();
Keishakeisling answered 4/12, 2017 at 13:34 Comment(1)
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.Berndt
B
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.

Broadwater answered 4/12, 2017 at 13:38 Comment(0)
D
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.

Dhole answered 4/12, 2017 at 13:36 Comment(2)
where can I find information about this? Can you include some source?Keishakeisling
The MDN documentation has some information.Dhole

© 2022 - 2024 — McMap. All rights reserved.