I have a user who is getting the error
TypeError: a is undefined
I'm confused how this can happen. Won't trying to access an undefined variable throw a reference error? In what situation could it throw a type error?
A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
A NameError will occur if you use a variable that has not been defined, either because you meant to use quotes around a string, you forgot to define the variable, or you just made a typo.
An undefined error is when we declare a variable in the code but do not assign a value to it before printing the variable.
An undefined variable in the source code of a computer program is a variable that is accessed in the code but has not been declared by that code. In some programming languages, an implicit declaration is provided the first time such a variable is encountered at compile time.
As pointed out by @jgillich in his answer, the following code produces a TypeError on an undefined object.
> a
ReferenceError: a is not defined
> var a;
> a.x
TypeError: a is undefined
To understand why, we can refer to ECMAScript 5.1 spec section 11.2.1 Property Accessors. We are interested in step 5
5. Call CheckObjectCoercible(baseValue).
In our example, baseValue is the value of the reference a. That means baseValue is undefined.
CheckObjectCoercible is defined in section 9.10
The abstract operation CheckObjectCoercible throws an error if its argument is a value that cannot be converted to an Object using ToObject. It is defined by Table 15:
And we can see in Table 15 that a TypeError is thrown for undefined and null values.
So the reason why we have a TypeErrorinstead of a ReferenceError is, as usual, because the spec says so!
There are other ways to obtain a TypeError on undefined, notably ToObject also throws a TypeError for undefined.
These three lines of code produce TypeError: can't convert undefined to object:
Object.defineProperties({}, undefined);
Object.prototype.toLocaleString.call(undefined);
Object.prototype.valueOf.call(undefined);
Though this time the message is a bit clearer.
Also invoking directly on undefined produces TypeError: undefined has no properties
undefined.foo();
undefined.x;
All of this was tested using Firefox 33.0a2 (Aurora).
> a
ReferenceError: a is not defined
> var a;
> a.x
TypeError: a is undefined
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