In recent years, JavaScript has developed very rapidly. Especially after the 2015 ES6 release, things got better.
Many new features are now proposed to be included in the ES2020 version. The good news is that these have been finalized. Now we have a finalized feature list that will appear in the highly anticipated ES2020 after being approved for release. Some of these features make me very excited because there will be a lot of trouble when writing code before they exist. Let's see what they are!
Optional Chaining Operator
For me personally, this is one of the most exciting features of ES2020. I've written a lot of programs that will benefit a lot from this new feature.
The optional chain operator allows you to securely access deep nested properties of an object without having to check if each property exists. Let's see how this feature helps us.
Before having optional chain operators
const user = { firstName: "Joseph", lastName: "Kuruvilla", age: 38, address: { number: "239", street: "Ludwig Lane", city: "Chennai", zip: "600028", prop1: { prop2: { prop3: { prop4: { value: "sample", }, }, }, }, }, }; if (user && ) { (); //600028 } if ( user && && .prop1 && .prop1.prop2 && .prop1.prop2.prop3 && .prop1.prop2.prop3.prop4 ) { (.prop1.prop2.prop3.); //sample } //Accessing unexisting property (.); //Error
As you can see above, you have to check if the property exists in each level to avoid errors where the undefined property "po" cannot be read. As the nesting level increases, the number of properties manually checked increases. This means we have to check each level to make sure it does not crash when encountering an undefined or empty object.
After having optional chain operators
With the introduction of Optional Chaining, our front-end work has become much easier. By simply using optional chain operators?.
We can access deep nested objects without having to check for undefined or empty objects.
Let's see how it works.
const user = { firstName: "Joseph", lastName: "Kuruvilla", age: 38, address: { number: "239", street: "Ludwig Lane", city: "Chennai", zip: "600028", prop1: { prop2: { prop3: { prop4: { value: "sample", }, }, }, }, }, }; (user?.address?.zip); // 600028 (user?.address?.prop1?.prop2?.prop3?.prop4?.value); // sample //Accessing unexisting property (user?.address?.prop102?.po); //undefined
So amazing! ES2020 successfully introduced a separate code operator?.
To reduce so many lines of code!
Nullish coalescing operator
This is another feature that excites me when I first went toproposal stage, When I learned about it, I sincerely liked this feature because I have experienced the hassle of writing separate functions to manually check this feature.
The null value merge operator allows you to checknullish
Value instead offalsey
value. Nullish value refers tonull
orundefined
value. And falsey values are such as empty strings, number 0,undefined
、 null
、 false
、 NaN
etc. This may sound no different to you, but in reality, it means a lot.
Let's see what's going on.
Before there is a null value merging operator
I recently did a project where I need to allow Dark Mode toggle functionality. I have to check that the input istrue
stillfalse
. If the user does not set any value, the default istrue
. Here is how I implement it before I have a null value merging operator:
const darkModePreference1 = true; const darkModePreference2 = false; const darkModePreference3 = undefined; const darkModePreference4 = null; const getUserDarkModePreference = (darkModePreference) => { if (darkModePreference || darkModePreference === false) { return darkModePreference; } return true; }; getUserDarkModePreference(darkModePreference1); // true getUserDarkModePreference(darkModePreference2); // false getUserDarkModePreference(darkModePreference3); // true getUserDarkModePreference(darkModePreference4); // true
After the null value merging operator
After the null value merging operator, all you have to do is use??
Operator. unnecessaryif
Statement:
const darkModePreference1 = true; const darkModePreference2 = false; const darkModePreference3 = undefined; const darkModePreference4 = null; const getUserDarkModePreference = (darkModePreference) => { return darkModePreference ?? true; }; getUserDarkModePreference(darkModePreference1); // true getUserDarkModePreference(darkModePreference2); // false getUserDarkModePreference(darkModePreference3); // true getUserDarkModePreference(darkModePreference4); // true
What basically happens here is if the variable darkModePreference contains anullish
value, then assign the value true to it. Simple, short, easy to understand.
Dynamic import (Dynamic Imports)
This feature will help your application execute more efficiently, and dynamic import allows you to dynamically import JS files as modules in native application applications. Before ES2020, modules should be imported regardless of whether they are used or not.
For example, suppose we need to add a feature to download a file in pdf format.
Let's see how to implement this before and after dynamic import.
Before dynamic import
In fact, no page visitors use the option to download pdf. However, whether our visitors use it or not, it still needs to be imported. This means that this pdf module can also be downloaded during page loading.
import { exportAsPdf } from "./"; const exportPdfButton = (".exportPdfBtn"); ("click", exportAsPdf);
This overhead can be reduced by using lazy loaded modules. It can be divided by code (code-splitting) method to implement this, which is already available in Webpack or other module packaging tools. But for ES2020, we can use it directly without the need for module packaging tools such as Webpack.
After dynamic import (dynamic import)
const exportPdfButton = ('.exportPdfBtn'); ('click', () => { import('./') .then(module => { () }) .catch(err => { // handle the error if the module fails to load }) })
As you can see in the above code, now the module is only delayed when it is needed. This reduces overhead and page loading time.
If you have a scenario where a task must be performed after all the promises are completed, then you may use()
method. But this method has one disadvantage. When any of your Promises are rejected, the Promise method will throw an error. This means your code won't wait until all the promises are done.
This may not be what you want. If you want something like this: "I don't care about their results. Just run them all" then you can use the new one()
method. This method is only available in all your Promisessettled
〼 OrResolved
, orRejected
〼 Only whenResolved
。
Before owning
const PromiseArray = [ (100), (null), ("Data release"), (new Error("Something went wrong")), ]; (PromiseArray) .then((data) => ("all resolved! here are the resolve values:", data) ) .catch((err) => ("got rejected! reason:", err)); //got rejected! reason: null
As mentioned above, when one of the Promises isrejected
Promise throws an error.
After having
const PromiseArray = [ (100), (null), ("Data release"), (new Error("Something went wrong")), ]; (PromiseArray) .then((res) => { (res); }) .catch((err) => (err)); //[ // {status: "fulfilled", value: 100}, // {status: "rejected", reason: null}, // {status: "fulfilled", value: "Data release"}, // {status: "rejected", reason: Error: Something went wrong ...} //]
Although some promises arerejected
, and returns all the results of the promises.
globalThis
globalThis
Contains references to global objects, regardless of the environment. In the browser, the global object iswindow
Object. In a Node environment, the global object isglobal
Or the in Web workersself
。
Before you have globalThis
At work, we need to write a common code that runs in both Node and browsers. When we want to obtain global objects, we usually need to do a lot of work and logical judgment:
beforeGlobalThis = (typeof window !== "undefined" ? window : (typeof process === 'object' && typeof require === 'function' && typeof global === 'object') ? global : this); = 'Little little bird, you can also show your grand plans';
After owning globalThis
We can use it directlyglobalThis
Reference global objects without worrying about the environment:
= 'Little little bird, you can also show your grand plans';
The above code is common in the browser or Node environment, and you can use it with confidence!
BigInt
Allows you to use numbers that are larger than the maximum allowed in Javascript. This number ispow(2,53)-1
. Although this is not backward compatible, as traditional digital systems (IEEE 754) cannot support numbers of this size.
matchAll()
is a method related to regular expressions. This method returnsRegular expressionsMatch all results of stringIterator, including capture groups. This method has been added to the String prototype.
Reference resources
ECMA
InfoQ
Article by Tyler Hawkins
Summarize
This article about ES2020 has been finalized, and this is the end of this article about real scene case analysis. For more related content about ES2020, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!