Uncaught ReferenceError: var is undefined when testing for truthy

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

Answers (3)

Vicky Gonsalves
Vicky Gonsalves

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);
}

fiddle

Upvotes: 2

James Allardice
James Allardice

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:

  • Evaluate the if statement [if ( Expression ) Statement]
    • This involves evaluating Expression, which returns a reference, as per 10.3.1
    • Call GetValue on the returned reference
      • If the reference is not resolvable (it's value is undefined), throw a reference error
    • Coerce the value of the reference to a boolean value

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

Praveen
Praveen

Reputation: 56509

var is a reserved keyword in Javascript.

The following is the corresponding error

Uncaught SyntaxError: Unexpected token var 

Upvotes: 0

Related Questions