What is Optional Chaining and Nullish Coalescing? (ES2020)

The Quick Answer

These are two of the new features to be implemented in the ES Standard in 2020. So while they don’t become official Javascript till next year they are already usable in Typescript 7.3 and in the latest version of Google’s V8 javascript engine which powers google chrome and node.

My Video illustrating both features: https://www.youtube.com/watch?v=1Vho–vDhQM

Optional Chaining

You sometimes will get runtime errors when you try to refer to an object property that does not exist. I have this issue often times with iterating arrays from API calls where some items in the array may not have a particular property.

in this situation I would have to do the following:

if (object.property){
variable = object.property;
}

With optional chaining, I can do the following…

variable = object?.property

The ‘?’ at the end of the property tell the interpreter to return null if the property doesn’t exist avoiding the runtime errors of the past and just looking a lot more elegant.

Nullish Coalescing

When establish a default value when there was uncertainty if the desired assignment has a value would usually be done like so…

myNewVariables = possibleVariable || defaultValue;

If possibleVariable had a truthy value it would assign it, if not, defaultValue would be assigned. The problem is the situations in which you may want to assign 0 or false. This method would evaluate those as falsely and assign the default value.

This is our new solution!

myNewVariables = possibleVariable ?? defaultValue;

This new ‘??’ operator will only return the default value if the first express is null or undefined, so 0 and false would be assigned.

Conclusion

New tools like these make our code more elegant and our stress in finding workarounds less. Although there is always the issue of browser compatibility which why typescript is such a killer tool. Use all the newest Javascript features plus typing and just compile down to ES5 when your done, no wonder typescript use is growing so quickly.

Leave a Reply

Your email address will not be published. Required fields are marked *