Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: var is undefined when testing for truthy

Tags:

javascript

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.

like image 272
André Alçada Padez Avatar asked Mar 23 '23 01:03

André Alçada Padez


1 Answers

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.

like image 185
James Allardice Avatar answered Apr 07 '23 01:04

James Allardice