I recently did a bit of bulk shopping at Costco to stock up on some food essentials. Like most stores, their price tags display the unit price for each item, so you can assess and compare the quality of each deal. Do you go with the small bag or the large bag? (Who am I kidding? It's Costco. Go large!)
But what if the unit price wasn't displayed?
- Optional Chaining
- Nullish Coalescing
- Dynamic Imports
You should note that not all browsers support these features — yet. If you want to start using these features now, make sure you provide appropriate polyfills or use a transpiler like Babel to ensure your code is compatible with older browsers.
If you want to follow along with your own copy of the code, first create a Heroku account and install the Heroku CLI on your machine. See this Heroku guide for installation instructions.
Once you’ve done that, you can create and deploy the project easily using the CLI. All of the source code needed to run this example app is available on GitHub.
Below are step-by-step instructions on how to clone the repo and deploy to Heroku:
git clone https://github.com/thawkin3/unit-price-calculator.git cd unit-price-calculator heroku create git push heroku master heroku open
My unit price calculator app is fairly simple: it lets you compare various price and weight options for fictional products and then calculates the unit price. When the page loads, it fetches product data from the server by hitting two API endpoints. You can then choose your product, your preferred unit of measurement, and a price/weight combination. The unit price calculation is done once you hit the submit button.
Now that you've seen the app, let's take a look at how I used all seven of those ES2020 features. For each feature, I'll discuss exactly what it is, how it's useful, and how I used it.
When a user first visits the calculator app, three API requests are kicked off to fetch product data from the server. We wait for all three requests to finish by using
Promise.allSettled() is a new feature that improves upon the existing
Promise.all() functionality. Both of these methods allow you to provide an array of promises as an argument, and both methods return a promise.
The difference is that
Promise.all() will short-circuit and reject itself early if any of the promises are rejected. On the other hand,
Promise.allSettled() waits for all of the promises to be settled, regardless of whether they are resolved or rejected, and then resolves itself.
So if you want the results from all your promises, even if some of the promises are rejected, then start using
Let's look at another example with
And now let's look at another example with
Promise.allSettled() to note the difference in behavior when a promise gets rejected:
Once the product data is fetched, we handle the response. The data coming back from the server contains an array of objects with deeply-nested properties. In order to safely access those properties, we use the new optional chaining operator:
Optional chaining is the feature I'm most excited about in ES2020. The optional chaining operator --
?. -- allows you to safely access deeply-nested properties of an object without checking for the existence of each property.
For example, prior to ES2020, you might write code that looks like this in order to access the
street property of some
In order to safely access the
street property, you first must make sure that the
user object exists and that the
address property exists, and then you can try to access the
With optional chaining, the code to access the nested property is much shorter:
If at any point in your chain a value does not exist,
undefined will be returned. Otherwise, the return value will be the value of the property you wanted to access, as expected.
When the app loads, we also fetch the user's preference for their unit of measurement: kilograms or pounds. The preference is stored in local storage, so the preference won't yet exist for first-time visitors. To handle either using the value from local storage or defaulting to using kilograms, we use the nullish coalescing operator:
The nullish coalescing operator --
?? -- is a handy operator for when you specifically want to use a variable's value as long as it is not
null. You should use this operator rather than a simple OR --
|| -- operator if the specified variable is a boolean and you want to use its value even when it's
For example, say you have a toggle for some feature setting. If the user has specifically set a value for that feature setting, then you want to respect his or her choice. If they haven't specified a setting, then you want to default to enabling that feature for their account.
Prior to ES2020, you might write something like this:
With the nullish coalescing operator, your code is much shorter and easier to understand:
As mentioned above, in order to get and set the user's preference for unit of measurement, we use local storage. For browsers, the local storage object is a property of the
window object. While you can just call
localStorage directly, you can also call it with
window.localStorage. In ES2020, we can also access it through the
globalThis object (also note the use of optional chaining again to do some feature detection to make sure the browser supports local storage):
globalThis feature is pretty simple, but it solves many inconsistencies that can sometimes bite you. Simply put,
globalThis contains a reference to the global object. In the browser, the global object is the
window object. In a node environment, the global object is literally called
Prior to ES2020, using an
Code splitting is incredibly useful for single page applications (SPAs). You can split your code into separate bundles for each page, so only the code needed for the current view is downloaded. This significantly speeds up the initial page load time so that end users don't have to download the entire app upfront.
Let's look at an example setup for the "Export PDF" functionality without dynamic imports:
And now let's look at how you could use a dynamic import to lazy load the large PDF download module:
When calling the
calculateUnitPrice method, we pass the product name and the price/weight combination. The price/weight combination is a string that looks like "$200 for 10 kg". We need to parse that string to get the price, weight, and unit of measurement. (There's certainly a better way to architect this app to avoid parsing a string like this, but I'm setting it up this way for the sake of demonstrating this next feature.) To extract the necessary data, we can use
There's a lot going on in that one line of code. We look for matches in our string based on a regular expression that is searching for digits and the strings "lb" or "kg". It returns an iterator, which we can then spread into an array. This array ends up with three elements in it, one element for each match (200, 10, and "kg").
This feature is probably the most difficult to understand, particularly if you're not well-versed in regular expressions. The short and simple explanation of
String.prototype.matchAll() is that it's an improvement on the functionality found in
RegExp.prototype.exec(). This new method allows you to match a string against a regular expression and returns an iterator of all the matching results, including capture groups.
Did you get all that? Let's look at another example to help solidify the concept:
Finally, we'll make the unit price calculation by simply dividing the price by the weight. You can do this with normal numbers, but when working with large numbers, ES2020 introduces the
BigInt which allows you to do calculations on large integers without losing precision. In the case of our app, using
BigInt is overkill, but who knows, maybe our API endpoint will change to include some crazy bulk deals!
Number.MAX_SAFE_INTEGER, which is 2^53 - 1.
If you tried to store a number larger than that value in a variable, sometimes the number wouldn't be stored correctly:
BigInt data type helps solve this problem and allows you to work with much larger integers. To make an integer a
BigInt, you simply append the letter
n to the end of the integer or call the function
BigInt() on your integer: