11

I am trying to access a certain member in a JavaScript object. In order to do this, I need to try out a couple of key values.

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

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

However, if alternatives exists instead of try catch blocks, that do achieve the same end goal, I would like to know about them as well.

EDIT:

I would prefer to use an exception over using functions. I do this because the text/html key might not be there, but it should be there. An exception seems more appropriate for this scenario

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • 3
    Missing keys return `undefined` in js, no errors are raised. – Ashwini Chaudhary Oct 11 '13 at 17:49
  • 3
    Related: http://stackoverflow.com/a/1098955/846892 – Ashwini Chaudhary Oct 11 '13 at 17:52
  • possible duplicate of [Checking if an associative array key exists in Javascript](http://stackoverflow.com/questions/1098040/checking-if-an-associative-array-key-exists-in-javascript) – Pointy Oct 11 '13 at 17:55
  • @Pointy Well that gives a way to do things, but is there an exception I could use? – Games Brainiac Oct 11 '13 at 17:57
  • 1
    @GamesBrainiac I don't think javascript likes [EAFP](http://docs.python.org/2/glossary.html#term-eafp) approach, so why do you want an exception? – Ashwini Chaudhary Oct 11 '13 at 18:02
  • @GamesBrainiac no; referencing a non-existent property is not an error in JavaScript. It's just an expression that evaluates to `undefined`. – Pointy Oct 11 '13 at 18:03
  • @hcwhsa Primarily because it _is_ an exception. The key is _supposed_ to be there, but it is not. This might very well happen, however. Thus, I believe that it is more appropriate to use an exception in this case. – Games Brainiac Oct 11 '13 at 18:04
  • See my answer. JS doesn't generate exceptions when reading or writing a property that doesn't exist. – jfriend00 Oct 11 '13 at 18:06
  • @GamesBrainiac But that's not an exception in js, you shouldn't write python code in js. Go for [LBYL](http://docs.python.org/2/glossary.html#term-lbyl). – Ashwini Chaudhary Oct 11 '13 at 18:09

2 Answers2

17

Javascript doesn't generate an exception when reading or writing a property that doesn't exist. When reading it, it just returns undefined. When writing it, it just creates the property.

You could create your own function that tests to see if the property exists and throws an exception if it does not (but you'd have to call that function whenever), but JS doesn't make an exception out of that on it's own like you are asking for.


If you want to test if a key exists on an object in javascript, you can use this construct 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 doesn't exist, you will get undefined as the value.

var obj = {};
var value = obj.test;

alert(value === undefined);

The in operator does a better job of telling you whether the key exists that testing for undefined because undefined is a legal value for a key that exists.


In many cases, where you control the values that the keys have and a key that is present will never have a falsey value, you can also just check if the key has a truthy 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 the property and not any prototype that it is inheriting from, then 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)
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thanks for giving the reason why exceptions cannot be used. I hope I could convey _why_ I needed one. Also, thanks for this answer, its more than suffice for my uses. – Games Brainiac Oct 11 '13 at 18:10
  • 3
    7 years later...probably solved it by this point...but I will add that `myObj.noKeyHere.noKeyHereEither` will result in a `TypeError` – Danny Sep 01 '20 at 16:58
0

Read this!

The accepted answer is correct however omits some points.

1) Accessing nested object

Like someone pointed out in the comment, Javascript returns undefined when the key doesn't exists in the object.

However, if you need to access an object inside an object (or an Array, or a function), well this break.

let a = {};
let userName = 'js'
let data = a.response[userName];

Cuz you will received actually a TypeError, basically because we are trying to read a property of undefined, which doesn't have any.

VM187:2 Uncaught TypeError: Cannot read properties of undefined (reading 'js')
    at <anonymous>:2:22

2 Answering the question

The Python principle "Ask forgiveness not permission" - explain is actually for the most part working well in Javascript (and PHP, you didn't ask but well..). There are for sure some difference, or some situation where the difference is important, but for most use cases is the same

So this is how you would do it:

try {
    let data = a.key1.key2['whatever'].nested.damn.object;
    console.log(data)
} catch (error) {
    let data = "noope"; 
    console.log(data);

}


As you can see, in Javascript you don't really care about the error type, (for the most part, sure other situation you should case). Is almost like anything is in a Python's

try:
   a = "hello" + 1 + {} + [] # crazy stuff here
except BaseException as bleh:
   print(str(bleh))

Documentatin

Federico Baù
  • 6,013
  • 5
  • 30
  • 38