I just read the article and I found it helpful but I am also confused about the definition.
It states the following:
A temporal dead zone (TDZ) is the area of a block where a variable is inaccessible until the moment the computer completely initializes it with a value.
Suppose you attempt to access a variable before its complete initialization. In such a case, JavaScript will throw a ReferenceError .
But this example contradicts that: let x; console.log(x); // returns undefined
If x is not completely initialized with a value it should return a ReferenceError as described in the article. Here x is only declared, it’s not completely initialized and has no value so why doesn’t it throw a ReferenceError?
Maybe I am just misunderstanding the explanation.
Does this mean that if no value is provided for x it will be hoisted AND initialized with undefined? Therefore, it now has a value and that’s why it doesn’t result in “ReferenceError”?
This would align with the article because we didn’t give x value but behind the scenes it was set to “undefined” so it’s “technically” initialized now?
Yes. Any variable that is declared without explicitly giving it a value will have its value set to undefined. Thus, a variable will always have a value when it is declared.
So your example above does not provide a contradiction. The variable x will have the value undefined when the console log is executed.
Now switch those two lines around and see what happens. Or switch them around and use var instead of let.