Access to a sometimes null object property without error

In javascript, I often want to access an 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 usual way to access the properties of potentially null objects and just return false or null if it does not exist?

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

+7
javascript
source share
3 answers

I don't think there is a direct equivalent to what you ask in JavaScript. But we can write some usage methods that do the same.

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

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

+2
source share

I would suggest

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

You can also add a control to property using:

 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 recognized as falsy value

+1
source share

If this is a frequent request for you, you can create a function that checks it, for example

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

All Articles