CodeNewbie Community

Cover image for What’s new in JavaScript after the ES2022 release?
Kai Wenzel
Kai Wenzel

Posted on

What’s new in JavaScript after the ES2022 release?

After the proposed new features reach stage 4, they will be added to JavaScript, which means:

  1. They have been approved by TC-39

  2. Passed testing and

  3. Have at least 2 implementations

Furthermore, features in stage 3 (which have been approved by TC-39 and passed the test but require implementation till now) may enter the ECMAScript by completing the implementations.

Top-level await operator

Asynchronous functions have been used in JavaScript for some time now. In the previous versions, developers could not declare the await keyword outside the asynchronous function. If done, it would show an error message. We can now use await at the top level of modules and don’t have to declare them inside async functions or methods anymore. This solves the synchronisation issue.

const res = await fetch('<https://swapi.dev/api/people/1/>');
const person = res.text();
Enter fullscreen mode Exit fullscreen mode

JavaScript modules will be capable of waiting for resources that require other modules to import them before rendering the code.

import { getUser } from './api/User';

const user = await getUser();
Enter fullscreen mode Exit fullscreen mode

Private fields and method declarations

You don’t have to invoke a constructor to declare a class field anymore. Now you can declare the class fields without calling the constructor. You can also directly declare the private class fields using the # symbol as the prefix.

class User {
  username;
  dateOfBirth;
  #address;
}
Enter fullscreen mode Exit fullscreen mode

You can also set the methods and accessors private using the same symbol, and we can also use getter and setter methods simultaneously with it.

class User {
  username;
  dateOfBirth;
  #address;
  get #address() {
    return #address;
  }
}
Enter fullscreen mode Exit fullscreen mode

Static class fields & private static methods

A static class field could not be accessed in instances of a class in the previous versions of JavaScript, other than via the prototype. The new addition of ES2022 features will give us the freedom to declare static class fields and private static features by using the keyword static.

class User {
  username;
  static userId;
  static get userId() {
   return userID;
  }
}
Enter fullscreen mode Exit fullscreen mode

The static keyword can be implied for cloning objects, caching, and fixed configuration.

Ergonomic brand checks for private fields

Private fields have a built-in “brand check”, in that if you try to access a private field on an object that does not have it installed, it throws an exception.

This is great! However, in order to keep the existence of a private field actually private, you would often want to check if an object has a private field, and if not, have some fallback behaviour (which might even be throwing a custom exception, with a message that does not reveal that I’m using a private field as my mechanism).

🚨 If you tried to access a public field that wasn’t declared in the previous versions, you would receive an undefined error. If you tried to access a private field, you would get an error message.

ES2022 introduces in operator to overcome this issue. By using the in operator, you will be able to check if a field is present in a class or not, even in the private classes.

class User {
  username;
  #address;

  set #address(addr) {
    #address = addr;
  }

  get #address() {
    return #address;
  }

  static hasAddress(obj) {
    return #address in obj;
  }
}
Enter fullscreen mode Exit fullscreen mode

Method .at() for indexing

The new method .at() of indexable values lets us read an element at a given index just like the bracket operator ([]) and supports negative indices (unlike the bracket operator). The bracket operator process was easy unless you had to conduct a backward iteration i.e. it required negative indexing. In the case of negative indexing, you had to refer to the string length and index from there. This process has been simplified by the use of the .at() function.

const fruits = ['apples', 'oranges', 'pears'];

console.log(fruits[fruits.length - 1]); // pears

console.log(fruits.at(0)); // apples
console.log(fruits.at(-1)); // pears
Enter fullscreen mode Exit fullscreen mode

Object.hasOwn()

Object.hasOwn() is a static method that returns true if the object has the specified property as its own property. If the property is inherited or does not exist, the method returns false.

const person = Object.create(null);
person.age = 21;

if (Object.hasOwn(person, 'age')) {
  console.log(person.age); // true - works regardless of how the object was created
}

if (person.hasOwnProperty('age')){ // throws error - person.hasOwnProperty is not a function
   console.log('hasOwnProperty: ', person.age);
}
Enter fullscreen mode Exit fullscreen mode

💡 It is recommended to use this method over the Object.hasOwnProperty() because it also works for objects created by using Object.create(null) and for objects that have overridden the inherited hasOwnProperty() method.

Although it's possible to solve this kind of problem by calling Object.prototype.hasOwnProperty.call(<object reference>, <property name>) on an external object, Object.hasOwn() is simpler to use:

const person = {
  hasOwnProperty: function() {
    return false;
  },
  age: 21
};

if (Object.hasOwn(person, 'age')) {
  console.log(person.age); // true - the remplementation of hasOwnProperty() did not affect the Object
}
Enter fullscreen mode Exit fullscreen mode

RegExp match indices

This new feature will allow you to use the character /d to express that you want the starting and ending indexes of the specified matching string. Previously this was not possible. You could only obtain indexing data in the process of string-matching operation.

To retrieve the list of matches:

  • You can use Regexp.exec — this will return all the results one after the other

  • String.matchAll — this will give you an iterator.

const fruits ="Fruits:apples, oranges, pears";
const regex = /(apples)/gd;
const matches = [...fruits.matchAll(regex)];

console.log(matches[0]);
Enter fullscreen mode Exit fullscreen mode

error.cause

The Error object and its subclasses now allow us to specify which error caused the current exception:

try {
  const result = 2 / 0;
  console.log(result);
} catch (error) {
  console.err(error);
  throw new Error('Something went wrong', { cause: error });
}
Enter fullscreen mode Exit fullscreen mode

Now the cause of the error err shows up in the stack trace and can be accessed via err.cause.

Temporal function

This is a stage 3 ES2022 JavaScript feature that is a substitute for the Date object. Date has been a long-standing pain point in ECMAScript. Temporal functions are expected to replace libraries such as moment.js. Temporal is a global object that will serve as the top-level namespace for the new date and time API, encompassing the entire spectrum of dates, times, calendars and time zones. It will function similarly to the Unix timestamp function.

const date = Temporal.Now.plainDateISO(); // Gets the current date
date.toString(); // returns the date in ISO 8601 date format

// If you additionally want the time:
Temporal.Now.plainDateTimeISO().toString(); // date and time in ISO 8601 format
Enter fullscreen mode Exit fullscreen mode

Summary

ES2022 JavaScript features have been launched in June 2022. However, the stage 3 features, including Temporal function, haven’t been released with the ES2022 update.

*That’s it and if you found this article helpful, please hit the ❤️, 🦄 button and share the article, so that others can find it easily :) *

If you want to see more of this content you can support me on Patreon!

Thanks for reading and hope you enjoyed!

Discussion (1)

Collapse
sjain profile image
surbhi nahta

Do you have the stuff to pro a Java Interview? We are here to help you in uniting your insight and ideas in Java. Before we start, we should comprehend what's truly going on with Java. Learn it from the Java Course in Pune.