Dmitry Parzhitsky Dmitry Parzhitsky - 1 year ago 54
Javascript Question

Why assigning to `NaN` or `undefined` cause error of this type?

A.S.: The question is about type of error, not about the phenomenon

"use strict"
throws TypeError if system variables like
got changed.

But why is it a TypeError? Why not SyntaxError?

Edit: Really, it is not the SyntaxError here since there are no errors in syntax of the snippet.

But the root of the error lies in the fact, that some protected object cannot be changed manually; so, it is lkely the AccessError (there are no such, I know).

Then, why access-errors appear like type-ones?

Answer Source

In ES5, there are 6 different kinds of native errors:

  • EvalError

    This exception is not currently used within this specification. This object remains for compatibility with previous editions of this specification.

  • RangeError

    Indicates a numeric value has exceeded the allowable range.

  • ReferenceError

    Indicate that an invalid reference value has been detected.

  • SyntaxError

    Indicates that a parsing error has occurred.

  • TypeError

    Indicates the actual type of an operand is different than the expected type.

  • URIError

    Indicates that one of the global URI handling functions was used in a way that is incompatible with its definition.

In your case, the error is thrown because you attempt to assign a value to window.NaN or window.undefined, which are non-writable properties.

Before assigning the new value, the internal [[Put]] method checks [[CanPut]], which will return false because the property is non-enumerable. And therefore [[Put]] will throw.

So the problem is that the writability of the assigned reference (left operand in the assignment expression) is not the expected one. Then, among the 6 error kinds above, the most appropriate seems TypeError, even if writability is not exactly a type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download