What's new in JavaScript?

April 21, 2020

You may have heard about the JavaScript committee, responsible for adding new features to the language. As Kyle Simpson’s succinctly puts it in his You Don’t Know JS Yet book:

The TC39 committee is comprised of between 50 and about 100 different people from a broad section of web-invested companies, such as browser makers (Mozilla, Google, Apple) and device makers (Samsung, etc).

If you are interested what features are currently under review, or have just made it to the language, you can check their GitHub page.

Since one of the most recent additions to JS are optional chaining and the Coalescing Operator, let’s take a closer look at them.

Optional chaining provides a fail-safe approach when accessing object’s properties. If a property on the object does not exist, we get a very common error “Cannot read property ‘X’ of undefined”.

In order to safe guard against that error, in the past we used to use the Short-Circuit Logic with the default value provided to solve this issue (see the code snippet below in red):

code snippet

However, now we can rely on the latest feature (in green).

When carousel does not exist and so the ? operator evaluates to either null or undefined, the whole expression will evaluate to undefined or thanks to the Coalescing Operator, ?? it will default to its value instead i.e. footerCarousel.slides:

definition of coalescing operator

I for one was very excited to see these two features introduced to JavaScript, as I have previously used them with C#. If you are still not convinced, as your code might seem not very readable at first, do give it some time. Try and use it on your project, and I think it will become clear how many lines of code it will save you.

Photo by Paul Esch-Laurent on Unsplash