Nullish Coalescing Operator
A logical operator that returns the right hand side if the left hand side is equal to null or undefined. Very similar behaviour to the logical OR operator
Optional Chaining Operator
Similar to the chaining operator but prevents errors from being thrown if object parameter reference does not exist. Instead the operator will short-circuit and return the value
Code Example Explanation
Above is a simple express server meant to depict a RESTful API. Focus your attention at line #39. Defined is an endpoint
/api/user/:id for partial updates to a user object in our database. To be more precise a PATCH request. Our problem comes from the client being able to send any permutation of parameters to be modified. For example the client might send data just to update the users first name,
This means that...
const last = updatedName.second
would return undefined and...
const streetName = updatedAddress.streetNumber
const streetNumber = updatedAddress.streetName
would both throw errors since the
address data field isn't even sent by the client.
So to guarantee a fallback and prevent errors due to undefined values we can use the nullish coalescent and optional chaining operators like in the following lines of code,
const first = updatedName?.first ?? user.name.first;
const last = updatedName?.second ?? user.name.last;
const streetName = updatedAddress?.streetNumber ?? user.address.streetNumber;
const streetNumber = updatedAddress?.streetName ?? user.address.streetName;
As of 2020, both the nullish coalescing and optional chaining operators are new additions to the ECMAScript standard. You will need to be running a version of node equal to or greater than 14.x.x to access to these tools.
In terms of frontend technologies, both these operators are now mostly supported in modern browser run-times but it is recommended to use babel transpiler plug-ins for support of older browsers (resources below)