Wow!!! ECMASCRIPT 2020 is here

Wow!!! ECMASCRIPT 2020 is here.In this article, we’re going to review some of the latest and greatest features coming with ES2020.

ECMAScript 2020, the lates version of the official specification underlying JavaScript, was formally approval by ECMA International, and the ECMA technical committee overseeing the specification, on June 16. 

Dynamic Import

If you had a file full of utility functions, some of them may rarely be used and importing all of their dependencies could just be a waste of resources. Now we can use async/await to dynamically import our dependencies when we need them

//math.js

const add = (num1, num2) => num1 + num2;

export { add };

//index.js


const doMath = async (num1, num2) => {
  if (num1 && num2) {
    const math = await import('./math.js');
    console.log(math.add(5, 10));
  };
};

doMath(4, 2);

BigInt and arbitrary precision integers

As you know, JavaScript has only one data type for numbers: the Number type. This primitive type allows you to represent 64-bit floating-point numbers. Of course, it also represents integers, but the maximum representable value is 253, corresponding to the Number.MAX_SAFE_INTEGER constant.

Without going into the internal details of integer representation, there are situations where you may need a higher precision. Consider the following cases:

  • interaction with other systems that provide data as 64-bit integers, such as GUIDs, account numbers, or object IDs
  • result of complex mathematical calculations requiring more than 64 bits.

The workaround for the first case is representing data as strings. Of course, this workaround doesn't work for the second case.

The new BigInt data type aims to solve these issues. You represent a literal BigInt by simply appending the letter n to a number, as shown in this example:
const aBigInteger = 98765432123456789n;
You can also use the BigInt() constructor the same way you use the Number() constructor:
const aBigInteger = BigInt("98765432123456789");
The typeof operator now returns the "bigint" string when applied to a BigInt value:
typeof aBigInteger      //output: "bigint"
Keep in mind that Number and BigInt are different types, so you cannot mix them. For example, the attempt to add a Number value to a BigInt value throws a TypeError exception.
Javascript Exception - ECMA Script 2020

Optional Chaining Operator

Similar to the nullish coalescing operator, JavaScript may not act how we want when dealing with falsy values. We can return a value if what we want is undefined, but what if the path to it is undefined?

By adding a question mark before our dot notation we can make any part of a value’s path optional so we can still interact with it.

let person = {};

console.log(person.profile.name ?? "Anonymous"); // person.profile is undefined
console.log(person?.profile?.name ?? "Anonymous");
console.log(person?.profile?.age ?? 18);

Private Class Variables

One of the main purposes of classes is to contain our code into more reusable modules. Because you’ll create a class that’s used in many different places you may not want everything inside it to be available globally.

Now, by adding a simple hash symbol in front of our variable or function we can reserve them entirely for internal use inside the class.

class Message {
  #message = "Howdy"

  greet() { console.log(this.#message) }
}

const greeting = new Message()

greeting.greet() // Howdy
console.log(greeting.#message) // Private name #message is not defined

The Promise.allSettled() method

Currently, JavaScript has two ways to combine promises: Promise.all() and Promise.race().

Both methods take an array of promises as an argument. The following is an example of using Promise.all():

const promises = [fetch("/users"), fetch("/roles")];
const allResults = await Promise.all(promises);
Promise.all() returns a promise that is fulfilled when all the promises fulfilled. If at least one promise is rejected, the returned promise is rejected. The rejection reason for the resulting promise is the same as the first rejected promise.

This behavior doesn't provide you with a direct way to get the result of all the promises when at least one of them is rejected. For example, in the code above, if fetch("/users") fails and the corresponding promise rejected, you don't have an easy way to know if the promise of fetch("/roles") is fulfilled or rejected. To have this information, you have to write some additional code.

The new Promise.allSettled() combinator waits for all promises to be settled, regardless of their result. So, the following code lets you know the result of every single promise:

const promises = [fetch("/users"), fetch("/roles")];
const allResults = await Promise.allSettled(promises);
const errors = results
  .filter(p => p.status === 'rejected')
  .map(p => p.reason);
In particular, this code lets you know the reason for the failure of each rejected promise.



Nullish Coalescing Operator

Because JavaScript is dynamically typed, you’ll need to keep JavaScript’s treatment of truthy/falsy values in mind when assigning variables. If we have a object with some values, sometimes we want to allow for values that are technically falsy, like an empty string or the number 0. Setting default values quickly gets annoying since it’ll override what should be valid values.

let person = {
  profile: {
    name: "",
    age: 0
  }
};

console.log(person.profile.name || "Anonymous"); // Anonymous
console.log(person.profile.age || 18); // 18
Instead of double pipes we can use the double question marks operator to be a bit more type strict, which only allows the default when the value is null or undefined.

console.log(person.profile.name ?? "Anonymous"); // ""
console.log(person.profile.age ?? 18); // 0

New operators

A couple of new operators will make it easier to write and to read your code in very common operations. Guess which ones?

The nullish coalescing operator

How many times you've seen and used expressions like the following?
const size = settings.size || 42;
Using the || operator is very common to assign a default value when the one you are attempting to assign is null or undefined. However, this approach could lead to a few potentially unintended results.
For example, the size constant in the example above will be assigned the value 42 also when the value of settings.size is 0. But the default value will also be assigned when the value of settings.size is "" or false. To overcome these potential issues, now you can use the nullish coalescing operator (??). The previous code becomes as follows:
const size = settings.size ?? 42;
This grants that the default value 42 will be assigned to the size constant only if the value of settings.size is null or undefined.

Optional chaining

Consider the following example:

const txtName = document.getElementById("txtName");
const name = txtName ? txtName.value : undefined;
You get the textbox with txtName as its identifier from the current HTML document. However, if the HTML element doesn't exist in the document, the txtName constant will be null. So, before accessing its value property, you have to make sure that txtName is not null or undefined.
The optional chaining operator (?.) allows you to have a more compact and readable code, as shown below:

const txtName = document.getElementById("txtName");
const name = txtName?.value;
As in the previous example, the name constant will have the the value of txtName.value if txtName is not null or undefined; undefined otherwise.
The benefits of this operator are much more appreciated in complex expressions like the following:

const customerCity = invoice?.customer?.address?.city;
You can apply the optional chaining operator also to dynamic properties, as in the following example:

const userName = user?.["name"];
n addition, it applies to function or method calls as well:

const fullName = user.getFullName?.();
In this case, if the getFullName() method exists, it is executed. Otherwise, the expression returns undefined.

Throughout this article, you got an overview of ES2020's new features, and you're probably wondering when you'll be able to use them.

According to caniuse.com, all recent major browsers but Internet Explorer already support the new features brought by ECMAScript 2020. However, at the time of writing, Safari is not supporting the new BigInt data type and the matchAll() method.

The latest version of Node.js supports all the features as well, including dynamic import for enabled ECMAScript modules.

Finally, also the latest versions of the most popular transpilers, like Babel and TypeScript, allow you to use the latest ES2020 features.

I know you all are excited for ECMAScript 2020.If you are interested in more such exciting news hit the subscribe button.I will always give my 100% efforts to bring you such a exciting news.That's all folks!!

Happy Coding!!!

Comments

Popular posts from this blog

Headlines are Zoom e2e encryption,Amazon's face recognition incorrectly matches,Android 11,Go 1.15 and What’s new is Angular 10 & Vue.Js 3.0

JAVA 14

Java 14 Continues.. new APIs of JDK14 and JVM Changes