Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>What is a ReferenceError?</h2> <p>As defined by ECMAScript 5, a <a href="http://es5.github.com/#x15.11.6.3" rel="noreferrer"><code>ReferenceError</code></a> indicates that an invalid reference has been detected. That doesn't say much by itself, so let's dig a little deeper.</p> <p>Leaving aside strict mode, a <code>ReferenceError</code> occurs when the scripting engine is instructed to get the value of a reference that it <a href="http://es5.github.com/#IsUnresolvableReference" rel="noreferrer">cannot resolve the <em>base value</em></a> for:</p> <blockquote> <p>A Reference is a resolved name binding. A Reference consists of three components, the base value, the referenced name and the Boolean valued strict reference flag. The base value is either undefined, an Object, a Boolean, a String, a Number, or an environment record (10.2.1). A base value of undefined indicates that the reference could not be resolved to a binding. The referenced name is a String.</p> </blockquote> <p>When we are referencing a property, the base value is the object whose property we are referencing. When we are referencing a variable, the base value is unique for each execution context and it's called an <em>environment record</em>. When we reference something that is neither a property of the base object value nor a variable of the base environment record value, a <code>ReferenceError</code> occurs.</p> <p>Consider what happens when you type <code>foo</code> in the console when no such variable exists: you get a <code>ReferenceError</code> because the <em>base value</em> is <em>not resolvable</em>. However, if you do <code>var foo; foo.bar</code> then you get a <code>TypeError</code> instead of a <code>ReferenceError</code> -- a subtle perhaps but very significant difference. This is because the <em>base value</em> was successfully resolved; however, it was of type <code>undefined</code>, and <code>undefined</code> does not have a property <code>bar</code>.</p> <h2>Guarding against ReferenceError</h2> <p>From the above it follows that to catch a ReferenceError before it occurs you have to make sure that the base value is resolvable. So if you want to check if <code>foo</code> is resolvable, do</p> <pre><code>if(this.foo) //... </code></pre> <p>In the global context, <code>this</code> equals the <code>window</code> object so doing <code>if (window.foo)</code> is equivalent. In other execution contexts it does not make as much sense to use such a check because by definition it's an execution context your own code has created -- so you should be aware of which variables exist and which do not.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload