New features in ES2022 JavaScript

Home » Programming » New features in ES2022 JavaScript
JS ES2022

New features in ES2022 JavaScript

Check out the features incorporated and usable in our JavaScript projects in the ES2022 version of ECMAScript, released this year.

  • Features of ES2022
    • Top-level await
    • Private instance fields, methods, and accessors
    • Static class fields and methods
    • Static class initialization blocks
    • Error: .cause
    • Array, String, and TypedArray: .at() Method
    • Object: .hasOwn()
    • RegExp: match .indices (‘d’ flag)

 

Top-level await

In the previous versions we could only use await in the scope of async functions. Now the await operator can declared even outside of the asynchronous functions and classes.

import { getFriends } from ‘./Friends’
let friendsObj = await getFriends(id);

 

Private instance fields, methods

In previous versions, declaring a private method or field required adding an underscore at the beginning of the method name (based on convention). However, this did not guarantee that the method would be private.

With ES2022 we get a new features as private instance fields, methods, and accessors. We just need to add # at the beginning of the method name, and that will declare it as private.

class User {
	// private class field
	#firstName = 'John';


	// private accessors
	get #name(){
		return 'John Doe';
	}


	// private class method  
	#addSchool(school){
		this.school = school
	}
}

const userObj = new User();
console.log("FirstName==", userObj.firstName) // undefined

console.log("Name==", userObj.name) // undefined

userObj.addSchool({name: 'English School'}); // Output: TypeError: userObj.addSchool is not a function

 

Private class fields, methods, accessors

 

Static class fields and methods

Static class fields and methods are not used on instances of a class. Instead, can be called on the class itself and is declared using the static keyword.

Often, developers use static methods as utility functions and helpers, while they employ static properties for caches or any other data that doesn’t need replication across instances.

class User {
	// static class fields
  	static firstName = 'John';


  	// static class methods
  	static message(){
		return 'This is a message from static method';
	}
}

console.log(User.firstName); // John

console.log(User.message()); // 'This is a message from static method';

 

Static class initialization blocks

class EvenOdd {
	static nums = [1, 2, 3, 4, 5, 6];
	static even = [];
	static odd = [];

  	// static class initialization block
  	static {
    	for (let number of this.nums) {
      		if (number & 1 !== 0) {
        	    this.odd.push(number);
      		} else {
                    this.even.push(number);
      		}
    	}
    }
}

console.log(EvenOdd.even) // [2, 4, 6]

console.log(EvenOdd.odd) // [1, 3, 5]

 

Error: .cause

Error and its subclasses now let us specify which error caused the current one:
For eg: new Error(‘Something went wrong’, {cause: otherError} )

const getFriends = async(id)=> {
  try {
    return await fetch('https://dummyapi/id');
  } catch (error) {
    throw new Error('Something when wrong', { cause: error })
  }
}

try{
  const friends = await getFriends(id);
} catch(error) {
  console.log(error); // Error
  console.log(error.cause); // TypeError: Failed (reason)
}

 

.at() Method

In the previous versions whenever we wanted to access elements from backward we have to calculate the length and subtract the number to get the element. For eg: arr[arr.length-1]

ES2022 came with a new feature of passing negative index in order to access elements from backwards

const daysInWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

console.log(daysInWeek.at(-1)); // Saturday


const holiday = 'Sunday';

console.log(holiday.at(-1)); // y

 

.hasOwn() Property

It is just as simplified version of hasOwnProperty

if (Object.hasOwn(object, "hi")) {
    console.log("has property")
}

 

RegExp: match .indices (‘d’ flag)

The new /d flag feature provides some additional information about the start and indices position end of each match in the input string.

const regex1 = /hello(\d)/dg;
const string1 = 'hello1hello2';
const result = [...string1.matchAll(regex1)];
console.log(result[0]);

 

To see which ES2022 features are supported by Nodejs, visit https://node.green/. You can also checkout the features of ES2021.