What are the new features in ES2020/ES10?
In this article, we will cover eight new features which were added in JavaScript ES2020/ES10.
1. BigInt
BigInt is a special numeric type that provides support for integers of arbitrary length. It provides a way to represent whole numbers larger than 2^53 - 1.
BigInt is created by appending n
to the end of integer or by calling function BigInt()
The following are the different ways of creating BigInt
.
const bigInt = 12345678901234567890n;
const bigIntAgain = BigInt("12345678901234567890");
const bigIntFromNumber = BigInt(10);
const hexToBigInt = BigInt("0x1fffffffffffff");
const binaryToBigInt = BigInt(
"0b11111111111111111111111111111111111111111111111111111"
);
2. Dynamic Import
The standard import syntax which we used is static and will always result in all code in the imported module being evaluated at load time. We can use dynamic import if we wish to load a module conditionally or on-demand.
In order to import a module dynamically, the import keyword may be called as a function. Dynamic import can be used as below.
if(true){
const dynamicModule = await import(./someModule.js);
}
dynamic import should be used only when necessary. The static form is preferable for initial loading dependencies.
3. Nullish Coalescing
The Nullish Coalescing(??) is a logical operator which returns its right-hand side operand if its left-hand side operand is null or undefined else returns its left-hand side operand. It has the ability to truly check nullish values instead of falsely values.
Syntax
leftExpr ?? rightExpr
const name = null;
const nameIs = name ?? "Pratap";
console.log(nameIs);
// expected output: "Pratap"
const number = 0 ?? 22;
console.log(number);
// expected output: 0
Nullish Coalescing can also be used while working with function
. It is also called Short-circuiting
.
function first() {
console.log("first was called");
return undefined;
}
function second() {
console.log("second was called");
return false;
}
function third() {
console.log("third was called");
return "foo";
}
console.log(first() ?? third());
// logs "first was called" then "third was called" and then "foo"
// as first() returned undefined so both expressions are evaluated
console.log(second() ?? third());
// logs "second was called" then "false"
// as second() returned false (and not null or undefined), the right
// hand side expression was not evaluated
4. Optional Chaining
The Optional Chaining operator ?.
permits accessing deeply nested property without worrying if the property exists or not. The ?.
operator functions similarly to the .
chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined.
const example = {
name: "Pratap",
channels: {
youtube: "https://www.youtube.com/channel/UCPPdMtAsDRqkk1Fve-HLfrA",
},
};
consoe.log(example.channels.youtube);
//https://www.youtube.com/channel/UCPPdMtAsDRqkk1Fve-HLfrA
consoe.log(example.channels.instagram);
// undefined
Further adding to Optional Chaining
let customer = {
name: "Pratap",
details: {
age: 24,
location: "Bangalore", // detailed address is unknown
},
};
let customerCity = customer.details?.address?.city;
// … this also works with optional chaining function call
let duration = vacations.trip?.getTime?.();
5. Promise.allSettled()
Promise.allSettled() method returns a promise which resolves after all of the given array of promises have either fulfilled or rejected. The array of result of the promise describes the outcome of each promise.
let apiCall1 = fetch("https://jsonplaceholder.typicode.com/posts");
let apiCall2 = fetch("https://jsonplaceholder.typicode.com/posts/1");
Promise.allSettled([apiCall1, apiCall2]).then((results) =>
results.forEach((result) => console.log(result))
);
Promise.allSettled([
Promise.resolve(22),
new Promise((resolve) => setTimeout(() => resolve(10), 0)),
1995,
Promise.reject(new Error("an error")),
]).then((values) => console.log(values));
//output
// [
// {status: "fulfilled", value: 22},
// {status: "fulfilled", value: 10},
// {status: "fulfilled", value: 1995},
// {status: "rejected", reason: Error: an error}
// ]
6. globalThis
The global globalThis
property contains the value of global this
, which is akin to the global object. globalThis
will always refer to the global object, no matter where you are executing your code.
function canSetTimeout() {
return typeof globalThis.setTimeout === "function";
}
console.log(canSetTimeout());
// expected output (in a browser): true
7. String.prototype.matchAll()
The matchAll() method returns an iterator which returns all matched group one after another.
let regexp = /t(e)(st(\d?))/g;
let str = "test1test2";
let array = [...str.matchAll(regexp)];
console.log(array[0]);
// Array ["test1", "e", "st1", "1"]
console.log(array[1]);
// expected output: Array ["test2", "e", "st2", "2"]
8. for...in
The for...in statement loops over all enumerable properties of an object like object
, array
etc. that are keyed by strings/index.
const object = { name: "Pratap", age: 24, address: "Bangalore" };
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
// expected output:
// "name: Pratap"
// "age: 24"
// "address: Bangalore"
Note: for...in should be ignored to iterate over an Array where the index order is important.
Conclusion
There are other many new features in ES2020/ES10. However, most of them don’t support the old browsers and are not stable in every environment. Before working you should consider which environments you are working on.
Further Reading
- My Monthly Update [May 2020]
- var, let, and const – Why to avoid var 😷 and how to put the other two to good use? - Javascript
💌 If you’d like to receive more tutorials in your inbox, you can sign up for the newsletter here.
Discussions