2

Is there any way in JavaScript to throw an error when I'm trying to access non existent object property?

inst.prop //Error
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
alex.mironov
  • 2,834
  • 6
  • 27
  • 41
  • 1
    Possible duplicate of http://stackoverflow.com/questions/6511542/force-javascript-exception-error-when-reading-an-undefined-object-property – Rakesh_Kumar Feb 04 '15 at 08:25

3 Answers3

7

Not presently, no, not on the object itself. ES2015+ offers proxies, and if you wrap the object in a proxy, you can then have the proxy throw an error when you try to read a property through the proxy that the underlying object doesn't have. But that would require wrapping in a proxy, and would require ES2015 support in the environment you're using (proxies can't be polyfilled). All up-to-date major JavaSript engines support proxies. If you're doing this on the web, the engines in slightly older browsers (IE11 for instance) don't support proxies and they cannot be polyfilled.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

The zealit Node package provides a way to that:

const zealit = require('zealit')

const ref = { foo: true, bar: undefined }
const zealed = zealit(ref)
zealed.prop // => will raise an error
Mick F
  • 7,312
  • 6
  • 51
  • 98
1

I'm not advanced or well-read enough to speak on the use of proxies. If I needed this type of functionality, I would opt to create a class with private properties and a getter method. The getter method would throw an error if an invalid key was passed.

MrNLK
  • 11
  • 1
  • 2
  • You can check the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields – Gerardo Perrucci Jul 16 '22 at 01:05