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?

Don P
  • 60,113
  • 114
  • 300
  • 432

3 Answers3

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/

Veera
  • 32,532
  • 36
  • 98
  • 137
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] );
}
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

steo
  • 4,586
  • 2
  • 33
  • 64