I have an inner function that references a variable initialized by its containing outer function:
function outer() {
function inner() {
if (foo) { ... }
}
let foo = 'bar';
inner(); // no error
};
However, there are some circumstances where the inner function may be invoked before the statement defining foo
has executed. In this case, any reference to foo
causes a ReferenceError in the inner function:
function outer() {
function inner() {
if (foo) { ... } // ReferenceError: foo is not defined
}
inner();
let foo = 'bar';
};
This is surprising to me, given that foo
has block scope, and I am within the enclosing block when executing the inner function.
More surprisingly is that even attempting to detect this situation with the typeof
operator - which I always understood to be a safe way to test for undefined variables - causes the same ReferenceError:
function outer() {
function inner() {
if (typeof foo !== 'undefined') { ... } // ReferenceError: foo is not defined
}
inner();
let foo = 'bar';
};
Edit: I now understand that this behavior is the result of the "temporal dead zone" involving let
and const
variables discussed elsewhere. However, I'm still looking for a clean, safe way to handle the situation.
Is there any safe way to test whether a block-scoped variable (e.g., one created with 'let' or 'const') has yet reached its declaration?