2

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

inst.prop //Error
1

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Right. Because it uses proxies, as I discussed in my answer.
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.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.