-1

In which specific cases does property access throw an error in JavaScript?

In Node.js, this prints undefined:

x = 3
console.log( x.thing );

This throws an error:

x = null;
console.log( x.thing );

What exactly is the semantics here? Property access is normal behavior for almost all values—even functions—but on undefined and null it throws an error.

I can't for the life of me find confirmation that those are the only cases. Can anybody confirm that?

Naman
  • 1,519
  • 18
  • 32
Alex
  • 780
  • 4
  • 12
  • 1
    What exactly do you expect `null.thing` to mean? – Pointy Jun 26 '17 at 22:47
  • It's quite simple, when you try to look for a property of a number, it checks the numbers prototype. Had you done `x.toString` you would have seen that it's a function. However `null` is explicitly a lack of identification, indicating that a variable points to **no** object – adeneo Jun 26 '17 at 22:50
  • I get all of that, I just don't know about other error cases. Are there any others? – Alex Jun 26 '17 at 22:57
  • `Property access is normal behavior for almost all values—even functions`, **No** this is wrong, in an object you can only access existing properties. For example in a string `str` you can only access existing properties such as `str.length` ... and properties that were not defined. – cнŝdk Jun 26 '17 at 23:03

1 Answers1

1

undefined and null are not references to objects, nor are they primitive values that can be implicitly boxed in object wrappers. Thus, any attempt to reference a property is going to fail.

When you use a number (3), the runtime boxes that as a Number instance, but of course there's no "thing" property so the value is undefined.

Also, functions are first-class objects, so references to properties on functions are not really "weird" in any sense.

Pointy
  • 405,095
  • 59
  • 585
  • 614