Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if property exists on potentially undefined object? [duplicate]

Tags:

So there are questions on S.O. that answer how to check if a property on an object exists. Example Answer is to use Object.prototype.hasOwnProperty().

However, how would you check the property of a potentially undefined object?

If one were to attempt to just directly check if a property exists on an undefined object then it would be a reference error.

Semantically, it seems better to check code directly if (obj.prop) //dosomething -- it shows clearer intent. Is there any way to achieve this? Preferably, is there a built-in Javascript method to do such a thing or by convention?

Motive: A package adds property user.session.email -- but I'm checking to see if email exists, not the session, though the session could be nonexistent.

Update: Many of the answers say to use the && operator to short-circuit. I'm aware that this is a possible solution, but it is not exactly what is desired as it seems like we're working AROUND the JS object syntax -- that is, though you want to really check for a property on an object, you are being forced to check if the object exists in order to do so.

Note to being marked as closed Why was this marked as closed? The link that presumes this is a duplicate may not yield the same answers. We're looking for a better, more semantic solution and marking this closed makes the assumption that "nested" === "potentially undefined".

This question is disputably closed: Since I can't answer my own question now. As of recently, a proposal was put in Stage 1 here that would solve this very issue. Again, the question wants a more semantic solution as is shown in the proposal.

like image 441
steviesh Avatar asked Aug 25 '16 02:08

steviesh


People also ask

How do you find out if a property is undefined?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.

How do you check if a property exists in an object TypeScript?

To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.

How do you check if an object has a specific property in JavaScript?

Object.prototype.hasOwnProperty() The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).


2 Answers

If you're certain the parent object exists, then:

if(obj && obj.key) {   console.log(obj.key); } 

However, this example will fail miserably if obj doesn't exist.

if (obj && obj.key) {    console.log(obj.key);  }

... which is why you might want to check if the object is defined when checking for the property. This ensures that you won't get runtime errors if the condition is hit and the property's object hasn't been set.

if(typeof obj != "undefined" && obj.key) {     console.log('you will not see this logged')  }

You'll notice that the above example does not throw an exception.

var obj = {key: 1};    if(typeof obj != "undefined" && obj.key) {    console.log('we have obj! and val is : ' + obj.key)  }

This is a much more defensive approach but it allows for portability. If you wanted to extract your logic into a module for reuse, you may want to check if the object exists as well or risk unwanted errors from an area of the application which you might not necessarily be concerned with.

like image 107
Seth Avatar answered Dec 16 '22 08:12

Seth


if you want to check both obj and prop exists (like you mentioned in your comments) you have to do:

if(obj && obj.hasOwnProperty('some')) or if(obj && obj.some)

As mentioned in comments this will throw error if obj is undefined. A better comparison would be would be:

if(typeof obj != "undefined" && obj.hasOwnProperty('some')) 
like image 33
Nishanth Matha Avatar answered Dec 16 '22 08:12

Nishanth Matha