Checking for optional properties and returning defaults in the expression language

With the Summer 2017 release there have been a couple of enhancements to the expression language to make it easier to check for the existence of properties in an object and returning a default value. Previously, you could use the ‘hasOwnProperty()’ method to check if a property is in an object. Now, objects have a ‘get()’ method to get the value of a property with the given name or return a default value.

For example, to get the value of the property named ‘optional’, you can do:

$.get('optional') // Returns the value of $optional or null

To get the property or a default value if the property is not found, you can do:

$.get('optional', 5)

Note that there is some subtlety here if the property can be in the object with a value of null. If you pass a default value to the ‘get()’ method and the property is in the object with a value of null, you will get a null result. So, if you wish to get a default if the property is not in the object or if it is null, you should use a logical or with the default value. For example:

$.get('nullable') || 5

In addition to the ‘get()’ method, we have added the ‘in’ operator as a shorthand for checking if a property is in an object.

'optional' in $

Error messages for undefined references have also been improved to try and suggest other properties in the object that have names similar to the one that was referenced. For example, in the following screenshot, there is no ‘ms’ field, but the object does have a ‘msg’ field.

Here is an exported pipeline that demonstrates some of these features:

optional-properties_2017_08_13.slp (4.8 KB)

6 Likes