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.

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.

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

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;
myNewVariables = possibleVariable ?? defaultValue;

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.

Alex Merced is a Full Stack Developer, learn more about his work at AlexMercedCoder.com

Alex Merced is a Full Stack Developer, learn more about his work at AlexMercedCoder.com