10

In javascript, I often want to access the attribute of an object that may not exist.

For example:

var foo = someObject.myProperty

However this will throw an error if someObject is not defined. What is the conventional way to access properties of potentially null objects, and simply return false or null if it does not exist?

In Ruby, I can do someObject.try(:myProperty). Is there a JS equivalent?

1
  • To check if its type is undefined is a way. Commented May 12, 2014 at 16:30

3 Answers 3

3

I don't think there's a direct equivalent of what you are asking in JavaScript. But we can write some util methods that does the same thing.

Object.prototype.safeGet = function(key) { return this? this[key] : false; } var nullObject = null; console.log(Object.safeGet.call(nullObject, 'invalid')); 

Here's the JSFiddle: http://jsfiddle.net/LBsY7/1/

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

2 Comments

handy handy handy, thanks
Object.prototype.safeGet crashes botbuilder for me.. strange...
2

If it's a frequent request for you, you may create a function that checks it, like

function getValueOfNull(obj, prop) { return( obj == null ? undefined : obj[prop] ); } 

Comments

0

I would suggest

 if(typeof someObject != 'undefined') var foo = someObject.myProperty else return false; //or whatever 

You can also add control on the property too, with:

if(someObject.myProperty) 

clearly inside the first if

Or ('maybe' less correct)

if(someObject) var foo = someObject.myProperty 

the second example should work because undefined is recognized as a falsy value

1 Comment

I think Don asks for a single line context, "if" context is obvious

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.