An operator from Groovy that I wish was in JavaScript
First off, keep in mind that I’ve never used Groovy, just skimmed a couple of language references, but people I know have used it and like it. In case anyone is not familiar, Groovy is a dynamic language implemented on the JavaVM. It’s commonly used for web development, especially with the Grails framework.
Anyway, having established that I don’t know much about Groovy, I do know that it has a feature that I really wish we had in JavaScript. It’s called the Safe Navigation Operator, and it’s represented as ?. in the code. Quoting the Groovy reference:
The Safe Navigation operator is used to avoid a NullPointerException. Typically when you have a reference to an object you might need to verify that it is not null before accessing methods or properties of the object. To avoid this, the safe navigation operator will simply return null instead of throwing an exception[.]
If it’s not clear from that, here’s a real-world example. Let’s say you have a customer object. That object has an optional attribute address, which is itself an object, and in turn has city, state, and postal code attributes, which are strings. In JavaScript, you could access the State like this:
var state = customer.state.address;
No problem, but what if the customer object doesn’t have an address? That line will throw an exception. We can work around it like this:
var customerState= customer.state ? customer.state.address : null;
But if we get deeply nested objects, the syntax gets really muddy. Using Groovy’s Safe Navigation Operator, we could just do this:
var customerState= customer?.state?.address;
Now, if customer is defined, and state is defined, and address is defined, then customerState has the customer’s state. Otherwise, it contains null. Either way, it never throws an exception, even if none of those objects are defined.
Cases where this could come in handy are data retrieved from deep XML hierarchies, complex nested JSON objects returned by web services, and unpredictable user-entered data. I’m sure that if JavaScript supported a similar operator I would use it all the time. Kudos to Groovy’s designer, Guillaume Laforge.