Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does reading a property sometimes throw an error in javascript?

Tags:

javascript

Suppose I have some variables:

var s = 's', i = 0, o = {}, a = [], n = null, nan = NaN, u;

How can I make any sense of when reading x.p will return undefined, and when it will throw a TypeError?

s.p;  // undefined
i.p;  // undefined
o.p;  // undefined
a.p;  // undefined
n.p;  // TypeError!
nan.p;  // undefined
u.p;  // TypeError!

P.S. Are null and undefined the only weird values in this way? Are there others?

Edit

I'm aware that by declaring variables as I have, several of my values have been automatically wrapped by objects (e.g. Number), despite being primitives. Therefore I can treat them like "proper" objects (e.g. {}, []) and attempt to read their properties. But I can't find much explaining what is and isn't wrapped this way.

like image 206
Chris Avatar asked Sep 15 '25 14:09

Chris


1 Answers

Yes, null and undefined are the only values that throw an exception when being used in a property access. The dot and bracket property accessors do invoke the internal CheckObjectCoercible function, which is defined as following:

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:

Table 15 — CheckObjectCoercible Results
Argument Type | Result
--------------+------------------
Undefined     | Throw a TypeError exception.
Null          | Throw a TypeError exception.
Boolean       | Return
Number        | Return
String        | Return
Object        | Return

null and undefined being the values that represent Nothing cannot be converted to objects ("wrapped" as you say). Notice that you could of course have an object with an existing property that throws on access, like

var o = {get p() { throw new TypeError("you may not access this"); }};
o.p // TypeError
like image 101
Bergi Avatar answered Sep 18 '25 04:09

Bergi