DEV Community

Alex Merced
Alex Merced

Posted on

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:

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 ({
variable =;
Enter fullscreen mode Exit fullscreen mode

With optional chaining, I can do the following...

variable = object?.property
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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


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.

Top comments (0)