So, I have always used the type of construction for testing the presence of variables:
if(foo){
doThings();
}
Now, I'm getting an
Uncaught ReferenceError: foo is undefined
Here's a fiddle
it's a fact that the var was never even declared. My question is, is this normal behaviour? I've used this many times and i think this is not the first time the variable is not declared; i'm almost sure that i never had a problem with this, it just returned false and didn't get in the condition.
Any help and clarification is welcome.
If a variable has not been declared then an attempt to reference it will result in a reference error.
If a variable has been declared but not assigned a value then it will implicitly have the value undefined
and your code will work as expected.
In your case, this is what happens:
if
statement [if ( Expression ) Statement]
undefined
), throw a reference error
The algorithm for determining the value of a reference traverses the chain of nested lexical environments until it reaches the outermost context. When it reaches that point and still does not find a binding for the provided identifier it returns a reference whose base value is undefined
.
When the base value of a reference is undefined
that reference is said to be "unresolvable", and when a reference is unresolvable any attempt to reference it will result (unsurprisingly) in a reference error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With