Equivalent of Python KeyError exception in JavaScript?

I am trying to access a specific member in a JavaScript object. To do this, I need to try a couple of key values.

For example, Object['text/html'] , which will give me an export link for an HTML document. However, not every object of this type will have the value of a text/html key pair.

In Python, I would solve this problem using a Try-Catch block, with the exception of KeyError . If I can do something similar in javascript, as if using an exception in a Try-Catch block, that would be great.

However, if there are alternatives instead of catch catch blocks that achieve the same end goal, I would like to know about them.

EDIT:

I would rather use an exception due to the use of functions. I do this because the text/html key may not be present, but it should be there. The exception looks more appropriate for this scenario.

+7
javascript python
source share
1 answer

Javascript does not throw an exception when reading or writing a property that does not exist. When reading, it just returns undefined . When writing it, it simply creates a property.

You can create your own function that checks if the property exists and throws an exception if it is not (but you will have to call this function every time), but JS does not make an exception to this, it belongs as you ask.


If you want to check if a key exists for an object in javascript, you can use this construction with the in operator:

 var obj = {}; var key = "test"; if (key in obj) { // key exists } else { // key doesn't exist } 

If you try to read a key that does not exist, you will get undefined as the value.

 var obj = {}; var value = obj.test; alert(value === undefined); 

The in operator knows better if a test key exists for undefined , since undefined is the legal value for a key that exists.


In many cases, when you control values ​​that have keys and the present key will never be falsey, you can also just check if the key has a true value:

 var obj = {}; var obj.test = "hello"; if (obj.test) { // key exists and has a truthy value } 

If you want to make sure that the object itself has a property, and not some prototype from which it is inherited, you can do this:

 var obj = {}; var obj.test = "hello"; if (obj.hasOwnProperty(test)) { // key exists on the object itself (not only on the prototype) } 
+8
source share

All Articles