1

I am new to ECMAScript 2015(ES6) and I am reading about temporal dead zones in ES6:

if(typeof x === "undefined") {
   console.log("x doesn't exist or is undefined");
} else {
// safe to refer to x....
}
let x = 5;  //script.js:1 Uncaught ReferenceError: x is not defined

Obviously in ES6 if you test a variable with typeof before declaring it throws errors

console.log(typeof x);
let x = 5;  //script.js:1 Uncaught ReferenceError: x is not defined

Why is this happening? Is this a bug?

Muge
  • 411
  • 5
  • 10
Combine
  • 2,868
  • 23
  • 28
  • 1
    "*if you test a variable*" - there's absolutely no reason to do that. You can just read the related code and see whether it's declared in the scope or not. This always can be statically determined (by the programmer or his tools), there is no need (and no way) to do it dynamically. – Bergi Apr 06 '16 at 10:39
  • Stop worrying about arcana and focus on how to write good programs, one aspect of which is to declare your variables at the top of the scope. –  Apr 06 '16 at 10:54

1 Answers1

4

That's the way it goes:

Temporal dead zone and errors with let

In ECMAScript 2015, let will hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
  • So if I can't use the variable before it is declared with "let" (which is obvious), how one can check if a variable is defined or not ? – Combine Apr 06 '16 at 08:30
  • 1
    obviously its a problem, that declared variables are from type undefined until an other value is applied. the best advice is to use as soon as possible a value which is not undefined, maybe null. – Nina Scholz Apr 06 '16 at 08:49