One of the best things about working in Javascript is that we have access to newer features every year, thanks to the hard work of TC39 committee and developers who implement the spec. There are a number of changes in ES2020, but this article covers the ones that specifically improve the experience of building apps in React.
It’s a common pattern in React component libraries to pass down event handler props, such as onClick
or onChange
. When these props are optional, the child component will often have to check for the existence of each to avoid the dreaded undefined is not a function
error. Optional chaining helps provide a concise one-liner, which is useful for interactive components with lots of event handlers.
Note: You can also use it for nested object properties e.g. props.userInfo?.lastName
Some components like controlled inputs often require deriving the value of state from multiple props. Prior to ES2020, a common way to have multiple fallbacks was using ternaries or ||
operators, which at times incorrectly led to omitting false-y values like 0
or '’
. The null coalescing operator guards against that by only applying the fallback when the value is null
or undefined
. Another benefit is that it provides much better readability than nested ternaries.
Note: You can also combine optional chaining with null coalescing operator, e.g. const userName = props.userInfo?.firstName ?? ‘User’
If you have experience with server-side rendering in React, you may have run into issues where objects assumed to be globally available are undefined
since the global object in node is global
, and in browser is window
. With globalThis
, there’s now a way to uniformly access the global object across platform. This is great for runtime dependencies fetched via a script tag but shimmed on server side, such as page analytics or translation utilities.
In addition to ones above, you can read about how to use features like dynamic imports, Promise.allSettled, and String.matchAll. Before using any of them, check whether your browser supports these features or make sure you have the necessary polyfills or build tools.
Thanks for reading!
#react #javascript #ES2020 #Programming