Access a property of a sometimes null object without an error
javascript
Solution
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/
Problem
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?