Introductory Guide to ES2021

Keeping up with programming language updates can be demanding. JavaScript’s ubiquitous nature is a reason the language is experiencing very consistent, fast, and frequent updates.

The Ecma International’s TC39 is a group of JavaScript developers, implementers, academics, and more, collaborating with the community to maintain and evolve the definition of JavaScript. They are doing an amazing job of keeping the language in the good shape. I appreciates the effort and do hope you do as well.

I will do a review of ES2021 (ECMAScript 2021) updates to the language.Show some of the syntax where appropriate with examples.

Prerequisites

You are expected to have a good understanding of JavaScript or Nodejs. If you are willing to keep up with the latest updates to the language then this is a best fit for you.

String.prototype.replaceAll

JavaScript language does not have a way to replace all of the occurence of a string value without the regular expression hack using global flag or a loop combined with String.prototype.replace.

// regex approach
let str = 'my name is ojo'
str.replace(/\s/g, '#')
// 'my#name#is#ojo'

// loop approach
while (/\s/g.test(str)) {
  str = str.replace(' ', '#')
  // 'my#name#is#ojo'
}

This introduce the String.prototype.replaceAll() to the language which is widely available in modern browsers. Check here for compatibility with old browsers. Check here for nodejs support. Support for this in nodejs starts from version 15.14.0.

You can polyfill with es-shims, corejs.

A polyfill is a function utility that can make the new features work in legacy browsers just by putting the polyfill code in your code. Polyfills gives you access to the features while they might not be ready in modern browsers.

let str = 'my name is ojo'
str.replaceAll(' ', '#')

Promise.any

Developers find it hard to make promises return the first occurence of a resolved or rejected promise, Promise.any proposes a solution to handle this use-case. It introduces something called Aggregate errors - Errors grouped in Array. Nodejs support for this feature starts from the version 15.14.0, while the browser support is implemented in all major browsers. Consider the following code snippet.

const promises = [
  fetch('/endpoint-a').then(() => 'a'),
  fetch('/endpoint-b').then(() => 'b'),
  fetch('/endpoint-c').then(() => 'c'),
]

try {
  const first = await Promise.any(promises)
  // Any of the promises was fulfilled.
  console.log(first)
  // → e.g. 'b'
} catch (error) {
  // All of the promises were rejected.
  console.assert(error instanceof AggregateError)
  // Log the rejection values:
  console.log(error.errors)
  // → [
  //     <TypeError: Failed to fetch /endpoint-a>,
  //     <TypeError: Failed to fetch /endpoint-b>,
  //     <TypeError: Failed to fetch /endpoint-c>
  //   ]
}

Numeric Separators

Numeric separators give more options for how numbers are formatted with separators. This proposal merges underscore separator proposal with numeric literal separator which allow a character separator between digits.Support for numeric separators in nodejs start in version 12.8.1 and all the major browsers support this proposal.

It comprises of Number literals support for Decimals and Binary, Hex, Octal, BigInt literal support. Let consider the following examples.

let num = 1_000_000
console.log(num)

WeakRefs and Logical Assignments Operators

The WeakRef proposal solve the two problem of

  • creating weak references to objects with the WeakRef class.
  • running user-defined finalizers after objects are garbage-collected, with the FinalizationRegistry class.

Support in nodejs start from the version 14.18.0 and all major browsers support this proposal.

Logical Assignments Operators on the other hand combines the assignment operator and the logical operators together. Just the way we can combine the assignment operator with mathematical operators in +=, -=, *=, /=. We now can have the following operators ||=, &&=, ??= which is “Or Or Equals” (or, the Mallet operator), “And And Equal”, “QQ Equals” respectively. Instead of doing a || (a = b) which interprets to a or b is assigned a, you can now a ||= b. Consider the following code snippet for the &&= and ??= usecases.

// "And And Equals"
a &&= b
a && (a = b) // if a is true then assign b to a
if (a) {
  a = b
}

// "Or Or Equals"
a ||= b
a || (a = b) // if a is false then assign b to a

// "QQ Equals"
a ??= b
a ?? (a = b) // if a is null or undefined then assign b to a

They are called the logical or assignment, logical and assignment and logical null coalescing operators. Nodejs support starts from 15.14.0 and are supported by all the major browsers. They have three main features:

  • basic support
  • short-circuiting behaviour
  • setter not unecessarily invoked

Conclusion

The updates are not much but the changes ES2020 brings solves a number of problem. It brings elegance to the way we write code, get to do more with less code.

Credit