Middle+
let x = 5; (function () { console.log(x); let x = 0; })()
sobes.tech AI
Answer from AI
This code will produce an error ReferenceError: Cannot access 'x' before initialization.
Why does this happen:
- Inside the function, a variable
xis declared usinglet. - Variables declared with
letandconstare in the "Temporal Dead Zone" from the start of the block until the declaration. - When calling
console.log(x), the variablexis already declared but not yet initialized, so accessing it causes an error.
If x inside the function was declared with var, the output would be undefined, because var is hoisted and initialized with undefined.
In summary: the code throws an error because of attempting to access a let variable before its declaration.