what's new in es2022?
2021-07-22

Co-author:

contributor avatar

Howdy, folks! The fact that you're here means you're looking for the new JavaScript features you can use in the close future. But by any chance, if you're not familiar with TC39, ECMA, or ECMAScript, check this article before reading this one, because you will need to know these to understand some of the following parts.

The transparent stages of the TC39

TC39 is an amazing and dedicated group of people who come from many different backgrounds and have one goal in common: they want to help to make the JavaScript language better. To do so, they have to keep many things in mind, and one rule they have is "don't break the web". Their approach to the language actually reminds me of the medical approach to the patients: "First, do no harm". Every step is carefully and meticulously calculated, so they don't break the existing parts.

Every feature that gets added to the spec has to go through the following 5 stages, just like drug trials. To proceed to the next stage, each has to achieve certain criteria. To be added to the ECMAScript spec, a feature has to be at least on stage 4.

  • Stage 0 / Proposal: A new possible feature that is planned to be presented to the committee, or proposals that haven't yet achieved the criteria to pass to the next stage. Check out the current stage 0 proposals from here.
  • Stage 1 / Proposal: Still primitive, but the committee is willing to spend time on solving this problem and the general structure of the API is defined. Check out the current stage 1 proposals from here.
  • Stage 2 / Draft: Critical aspects of the proposal and its problems are solved. These features are expected to exist in future versions of the spec. Check out the current stage 2 proposals from here.
  • Stage 3 / Candidate: The proposal is comprehensively and meticulously reviewed, no stone is left unturned. This is the final stage before the feature actually makes it to the spec. Check out the current stage 3 proposals from here.
  • Stage 4 / Finished: Congrats, you are in the spec! Check out the finished proposals from here.

The ones who made it before

JavaScript is an evolving language, and some features we use today were actually added pretty recently. After 2015, TC39 decided to make the changes annually, so each year they decide which new features are ready to be added. This is the list of the features that have been added to the spec after 2015:

ES2016

  • Array.prototype.includes(): Determines if a given element is included in the specified array. String.prototype.contains() was also deprecated and String.prototype.includes() was added to determine if a given string in included in another string.
  • Exponentiation operator(** and **=): a**b is shorthand notation for Math.pow(a,b), and a **= b is shorthand for a = a**b

ES2017

  • Object.values / Object.entries: Retrieves an array of values / arrays of key-value pairs, respectively.
  • Trailing commas in function parameter lists and calls: Both (a) => {} and (a,) => {} are valid function definitions, and both foo(a) and foo(a,) are valid function calls.
  • Async functions: async/await was introduced to JavaScript
  • Object.getOwnPropertyDescriptors(): Returns the property descriptors of all own properties of an object.
  • String.prototype.padStart() / String.prototype.padEnd(): Takes two arguments, first one being the repeat number, second one being the string that is going to be added and adds padding to the start or end of a given string.

ES2018

  • Promise.prototype.finally: Finally was introduced to register a callback function that runs when a promise is settled (either fulfilled or rejected)
  • Rest and spread operators(...): Rest operator collects values in an array. The spread operator spreads the values in an iterator.
  • Asynchronous iteration: for-await-of was introduced. It is a variation of the for-of iteration statement and can be used in async iterable objects.
  • Improvements on Regular Expressions: RegExp Unicode Property Escapes, RegExp Lookbehind Assertions, s(dotAll) flag for regular expressions, RegExp named capture groups

ES2019

  • Array.prototype.flat(): Flattens nested arrays up to a provided depth. Default depth is 1.
  • Array.prototype.flatMap(): Flattens and maps a given array subsequently. Flattening depth is 1.
  • Object.fromEntries(): Builds an object from given key-value pairs.
  • String.prototype.trimStart(): Trims the start of a given string.
  • String.prototype.trimEnd(): Trims the end of a given string.
  • Symbol.prototype.description: Read-only and optional string description for the Symbol objects.
  • Optional catch binding: Allows the omission of the catch block.
  • Also the implementation of some existing features have changed, such as JSON.stringify(), Function.prototype.toString() and Array.sort()

ES2020

  • String.prototype.matchAll(): Returns all matches for a global regex.
  • dynamic imports: Before this, we could only use static imports, which only accepted strings for the module path. With dynamic imports, we got to conditionally import modules by using promises.
  • BigInt: A new primitive data type that represents numbers bigger than 2⁵³.
  • Promise.allSettled(): Returns when all given promises are settled (rejected or fulfilled, doesn't matter).
  • globalThis: Before this, the global object had different syntax in different JavaScript environments (in a web browser it can be either window, self, frames, or this, in web workers it is self, in Node.js it is global). globalThis provided a single syntax for the global object in all JavaScript environments.
  • Optional Chaining Operator(?.): Legible property chains that don't throw an error if a requested reference is missing. If one of the chained properties is nullish (null or undefined), the whole expression returns undefined.
  • Nullish coalescing operator(??): Binary operator. If the value of the left side expression is null or undefined, the right side of the operator is evaluated.

ES2021

  • String.prototype.replaceAll(): Replaces all the occurrences of a given string with another.
  • Promise.any(): resolves if any of the given promises are resolved.
  • Underscore as a numeric separator: To increase legibility in bigger numbers, numeric separators can be replaced with underscores.
  • Logical assignment operators(&&=, ||=, ??=) All of them are binary operators, with the added functionality for assignment. For &&=, if the left side is truthy, the right-side expression is evaluated and assigned to the variable on the left side. For ||= if the left side is falsy, the right-side expression is evaluated and assigned to the left-side variable. With the ??=, if the left-side value is null or undefined, the right-side expression is evaluated and assigned to the variable on the left side.
  • WeakRefs and Finalizers: This is a class that helps you create weak references to objects, so they can be garbage collected. A FinalizationRegistry object lets you register a callback that will allow you to invoke when the object is garbage collected.

The ones who made it to ES2022

Alright! You can check the latest spec that was published from here.

1. Class Fields:

  • Class Public Instance Fields & Private Instance Fields:

    Since ES2015, we could define fields by simply setting them up in our constructors. As a convention, fields that were not supposed to be accessed outside of the class methods were preceded by an underscore, but this did not stop any consumer of this class from accessing them anyway.

    class ColorButton extends HTMLElement {
      
      constructor() {
        this.color = "red"
        this._clicked = false
      }
    }
    
    const button = new ColorButton()
    // Public fields can be accessed and changed by anyone
    button.color = "blue" 
    
    // Curse your sudden but inevitable betrayal 
    console.log(button._clicked) // Prints: false, can be accessed from the instance
    button._clicked = true // Doesn't throw an error, can be read from the instance

    The first part of this proposal offers a more clear way to define the fields in a class. Instead of defining them in our constructor, we can now define, and if we want to, initialize them on the top level of our classes.

    class ColorButton extends HTMLElement {
      color = "red"
      _clicked = false
    }

    The second part offers a more secure way of hiding private fields from prying eyes. Instead of the conventional underscore, we can now use a preceding # in the field names to block anybody from accessing them outside of the class they're defined on.

    class ColorButton extends HTMLElement {
      // All fields are public by default
      color = "red"
    
      // Private fields start with a #, can only be changed from inside the class
      #clicked = false
    }
    
    const button = new ColorButton()
    // Public fields can be accessed and changed by anyone
    button.color = "blue"
    
    // SyntaxError here 
    console.log(button.#clicked) // Cannot be read from outside
    button.#clicked = true // Cannot be assigned a value from outside
  • Private instance methods and accessors:

    Some methods and variables of a class are internally important for that class to behave like it's supposed to, but shouldn't be accidentally reached from outside. To protect these implementation details and keep them strictly internal, we can use private methods and accessors with the syntax of a preceding #.

    class Banner extends HTMLElement {
      // Private variable that cannot be reached directly from outside, but can be modified by the methods inside:
    
      #slogan = "Hello there!"
      #counter = 0
    
      // private getters and setters (accessors):
    
      get #slogan() {return #slogan.toUpperCase()}
      set #slogan(text) {this.#slogan = text.trim()}
    
      get #counter() {return #counter}
      set #counter(value) {this.#counter = value}
    
      constructor() {
        super();
        this.onmouseover = this.#mouseover.bind(this);
      }
    
      // private method:
      #mouseover() {
        this.#counter = this.#counter++;
        this.#slogan = `Hello there! You've been here ${this.#counter} times.`
      }
    }
  • Static class fields and private static methods:

    Static class fields and methods are useful when you want certain fields and methods to only exist in the prototype, but not in every instance of the given class. On the other side, you might also want to allow some of these fields and methods to be only accessed from within the class.

    Since ES2015, we can define static fields on a class by simply defining the field on the class itself.

    class Circle {}
    Circle.PI = 3.14

    Going forward, we are now able to define these static fields inside the class definition using the static keyword.

    class Circle {
      static PI = 3.14
    }

    Just like we did with class fields and methods, we can use the # prefix to set any static method or field as private. This prevents access to these static fields and methods from the outside, meaning they can only be accessed from inside the class.

    class Circle {
      static #PI = 3.14
    
      static #calculateArea(radius) {
        return #PI * radius * radius
      }
    
      static calculateProperties(radius) {
        return {
          radius: radius,
          area: #calculateArea(radius)
        }
      }
    
    }
    
    // Public static method, outputs {radius: 10, area: 314}
    console.log(Circle.calculateProperties(10))
    
    // SyntaxError - Private static field
    console.log(Circle.PI)
    
    // SyntaxError - Private static method
    console.log(Circle.calculateArea(5))

2. Ergonomic brand checks for Private Fields:

In public fields, if you try to access a non-existent field on a class, you get undefined as a result. However, private class fields throw an exception instead of returning undefined when you try to access a non-existent field on an object. Then, one way to check if a private field exists in an object is to see if accessing that field inside the class throws an exception or not. However, this approach has a big shortcoming. The exception might simply be because of another reason, such as a faulty getter on an existing field.

That's why, in keyword was proposed to allow us to check if a given private property/method exists in a class instance:

class VeryPrivate {
  constructor() {
    super()
  }

  #variable
  #method() {}
  get #getter() {}
  set #setter(text) {
    this.#variable = text
  }

  static isPrivate(obj) {
    return (
      #variable in obj && #method in obj && #getter in obj && #setter in obj
    )
  }
}

3. RegExp Match Indices

Regular expressions allow us to search for patterns in strings. If you're not familiar with regular expressions, you might want to start by reading this article first.

Both Regexp.exec and String.matchAll gives us a list of matches as a result. Regexp.exec gives these results one by one, so you need to call it multiple times to get all matches until it returns null. On the other hand String.matchAll returns an iterator where you can iterate over all matches. These results include both the full string of characters and the parenthesized substrings being matched, the input string and the 0-based index of the match. Take a look at the following example:


const str = 'Ingredients: cocoa powder, cocoa butter, other stuff'
const regex = /(cocoa) ([a-z]+)/g
const matches = [...str.matchAll(regex)]

// 0: "cocoa powder", 1: "cocoa", 2: "powder"
// index: 13
// input: "Ingredients: cocoa powder, cocoa butter, other stuff"
console.log(matches[0])


// 0: "cocoa butter", 1: "cocoa", 2: "butter"
// index: 27
// input: "Ingredients: cocoa powder, cocoa butter, other stuff"
console.log(matches[1])

While these results are pretty informative about the location of the entire match in the original input, they lack information regarding the indices of the substring matches. By using the new /d flag, we can ask for the start and end positions of each matched capture group.


const str = 'Ingredients: cocoa powder, cocoa butter, other stuff'
const regex = /(cocoa) ([a-z]+)/gd
const matches = [...str.matchAll(regex)]

// 0: "cocoa powder", 1: "cocoa", 2: "powder"
// index: 13
// input: "Ingredients: cocoa powder, cocoa butter, other stuff"
// indices: [[13,25],[13,18],[19,25]]
console.log(matches[0])


// 0: "cocoa butter", 1: "cocoa", 2: "butter"
// index: 27
// input: "Ingredients: cocoa powder, cocoa butter, other stuff"
// indices: [[27,39],[27,32],[33,39]]
console.log(matches[1])

4. Top-level await:

Until this point, we could only use await in the scope of async functions. This was fine until it wasn't, like when we hit the top level of our module and could not use the await keyword. Now await can be used at the top level of a module, and can be super handy when initializing imports and creating fallbacks.

Here's an example:

// Before the top-level await, JavaScript would have given you a SyntaxError with this line of code, but that is no more
await Promise.resolve(console.log("🎉"))

So until the awaited promise is resolved, the execution of the current module and the parent module that imports the current child module are deferred, but the sibling modules can be executed in the same order. Check this article out to see more examples.

Resources

  1. ECMAScript® 2022 Language Specification
  2. Top-level await by v8.dev
  3. github.com/tc39/proposals
robot illustration hanging at the bottom of the page