JavaScript ES2020: New Features and Improvements

ECMAScript 2020, also known as ES11, introduced several new features and improvements to the JavaScript language. This article will explore the key additions and how they can enhance your JavaScript development experience.

1. Optional Chaining (?.)

The optional chaining operator allows you to safely access nested object properties without worrying about whether the property exists. This helps prevent errors when dealing with potentially undefined or null values.

Example:

const user = {
  name: "John",
  address: {
    street: "123 Main St"
  }
};

console.log(user.address?.zipCode); // Outputs: undefined

2. Nullish Coalescing Operator (??)

This operator provides a way to handle default values for null or undefined, without treating falsy values like 0 or an empty string as null.

Example:

const count = 0;
const result = count ?? 42;
console.log(result); // Outputs: 0

3. BigInt

BigInt is a new numeric primitive that can represent integers with arbitrary precision. This is especially useful when working with very large numbers that are outside the range of the Number primitive.

Example:

const bigNumber = 1234567890123456789012345678901234567890n;
console.log(typeof bigNumber); // Outputs: "bigint"

4. Promise.allSettled()

This new Promise method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describe the outcome of each promise.

Example:

const promises = [
  Promise.resolve(1),
  Promise.reject("error"),
  Promise.resolve(3)
];

Promise.allSettled(promises).then(results => console.log(results));
// Outputs: [
//   { status: "fulfilled", value: 1 },
//   { status: "rejected", reason: "error" },
//   { status: "fulfilled", value: 3 }
// ]

5. globalThis

The globalThis property provides a standard way of accessing the global this value across different JavaScript environments.

Example:

console.log(globalThis === window); // true in browsers
console.log(globalThis === global); // true in Node.js

Conclusion

ES2020 brought several useful features to JavaScript, improving developer productivity and code readability. By incorporating these new features into your projects, you can write more concise and robust code.