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?
You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device.
To set all values in an object to null , pass the object to the Object. keys() method to get an array of the object's keys and use the forEach() method to iterate over the array, setting each value to null . After the last iteration, the object will contain only null values.
null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.
In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral ("null") behavior. The null object design pattern describes the uses of such objects and their behavior (or lack thereof).
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/
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] );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With