Reputation: 11598
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.
Upvotes: 4
Views: 1462
Reputation: 11717
check the updated fiddle. If you haven't declare a variable then in condition u will have to check its type.
var a = 1;
var b;
try{
if(typeof(c)!='undefined') {
alert("OK");
}
} catch(ex){
alert(ex);
}
Upvotes: 2
Reputation: 165971
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]
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.
Upvotes: 5
Reputation: 56509
var
is a reserved keyword in Javascript.
The following is the corresponding error
Uncaught SyntaxError: Unexpected token var
Upvotes: 0