Amazing New JavaScript Features in ECMAScript 2022 (ES13)
1. Class Field Declarations
In the new ECMAScript 2022, we can define the class field declarations as mentioned below. As we can see, now we can directly intialize the property's default value. Now we don't need a constructor for that.
//NEW ECMAScript 2022
class User1 {
firstName = 'Core';
middleName = 'Knowledge';
lastName = 'Sharing';
}
const user1 = new User1();
console.log(user1.firstName); // Core
console.log(user1.lastName); // Sharing
//ECMAScript 2021 OR Before ECMAScript 2022
class User2 {
constructor() {
this.firstName = 'Core';
this.middleName = 'Knowledge';
this.lastName = 'Sharing';
}
firstName;
middleName;
lastName;
}
const user2 = new User2();
console.log(user2.firstName); // Core
console.log(user2.lastName); // Sharing
2. Private Methods and Fields
In the new ECMAScript 2022, we can define private fields and members to a class by prefixing them with the hashtag (#) symbol. If we try to access this outside the class, it will throw an error, as mentioned below In older versions, we were able to access and modify the private variable outside the class.
//NEW ECMAScript 2022
class Person1 {
#firstName = 'Ankush';
#lastName = 'Agnihotri';
get name() {
return `${this.#firstName} ${this.#lastName}`;
}
}
const person1 = new Person1();
console.log(person1.name);
// SyntaxError: Private field '#firstName' must be
// declared in an enclosing class
console.log(person1.#firstName);
console.log(person1.#lastName);
//ECMAScript 2021
class Person2 {
_firstName = 'Core';
_lastName = 'Knowledge Sharing';
get name() {
return `${this._firstName} ${this._lastName}`;
}
}
const person2 = new Person2();
console.log(person2.name); // Core Knowledge Sharing
// Members intended to be private can still be accessed
// from outside the class
console.log(person2._firstName); // Core
console.log(person2._lastName); // Knowledge Sharing
// They can also be modified
person2._firstName = 'Ankush';
person2._lastName = 'Agnihotri';
console.log(person2.name); // Ankush Agnihotri
3. Await Operator at the Top Level
In the new ECMAScript 2022, we can use await without the async keyword to method. See the below example:
//NEW ECMAScript 2022
function setTimeoutAsync(timeout) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, timeout);
});
}
// Waits for timeout - no error thrown
await setTimeoutAsync(3000);
//ECMAScript 2021
// SyntaxError: await is only valid in async functions
await setTimeoutAsync(3000);
4. Static Class Fields and Static Private Methods
In the new ECMAScript 2022, we can declare static fields and static private methods for a class. Static methods can access other private/public static members in the class using the this
keyword, and instance methods can access them using the this.constructor,
as mentioned below.
class Person {
static #count = 0;
static getCount() {
return this.#count;
}
constructor() {
this.constructor.#incrementCount();
}
static #incrementCount() {
this.#count++;
}
}
const person1 = new Person();
const person2 = new Person();
console.log(Person.getCount()); // 2
5. Class static Block
In the new ECMAScript 2022, we can give the definition of static
blocks that will be executed only once at the creation of the class. A class can have any number of static {}
initialization blocks in its class body in the order they are declared. We can use the super
property in a static
block to access properties of the super class.
class Vehicle {
static defaultColor = 'blue';
}
class Car extends Vehicle {
static colors = [];
static {
this.colors.push(super.defaultColor, 'red');
}
static {
this.colors.push('green');
}
}
console.log(Car.colors); // [ 'blue', 'red', 'green' ]
6. Exist Checks for Private Fields
In the new ECMAScript 2022, we can check the existance of any private field inside the class using an in operator, as shown below.
class Car {
#color;
hasColor() {
return #color in this;
}
}
const car = new Car();
console.log(car.hasColor()); // true;
7. at() Method for Indexing
In the new ECMAScript 2022, we will use the at() method more benificially for the the nth index of array. See the below example:
//NEW ECMAScript 2022
const arr = ['a', 'b', 'c', 'd'];
// 1st element from the end
console.log(arr.at(-1)); // d
// 2nd element from the end
console.log(arr.at(-2)); // c
const str = 'Core Knowledge Sharing';
console.log(str.at(-1)); // g
console.log(str.at(-2)); // n
const typedArray = new Uint8Array([16, 32, 48, 64]);
console.log(typedArray.at(-1)); // 64
console.log(typedArray.at(-2)); // 48
//ECMAScript 2021
const arr = ['a', 'b', 'c', 'd'];
// 1st element from the end
console.log(arr[arr.length - 1]); // d
// 2nd element from the end
console.log(arr[arr.length - 2]); // c
8. RegExp Match Indices
The new ECMAScript 2022 allows us to specify whether we want the get both the starting and ending indices of the matches of a RegExp
object in a given string.
Previously, we could only get the starting index of a regex match in a string.
const str = 'sun and moon';
const regex = /and/;
const matchObj = regex.exec(str);
//NEW ECMAScript 2022 Output
// [ 'and', index: 4, input: 'sun and moon', groups: undefined, indices: [ [ 4, 7 ], groups: undefined ] ]
console.log(matchObj);
//ECMAScript 2021 Output
// [ 'and', index: 4, input: 'sun and moon', groups: undefined ]
console.log(matchObj);
9. Object.hasOwn() Method
In the new ECMAScript 2022, we can use the Object.hasOwn()
method to check if an object has a given property. In previous versions, we could check this via the Object.prototype.hasOwnProperty(), but the issue with that is that we can override this method. It will give us a false result, as shown below.
const obj = Object.create(null);
obj.color = 'green';
obj.age = 2;
obj.hasOwnProperty = () => false;
console.log(Object.hasOwn(obj, 'color')); // true
console.log(Object.hasOwn(obj, 'name')); // false
console.log(car.hasOwnProperty('age')); // false
console.log(car.hasOwnProperty('name')); // false
10. Error Cause
In the new ECMAScript 2022, Error objects now have a cause
property for specifying the original error that caused the error that is about to be thrown. This helps to add additional information to the error for diagnoses of unexpected behavior(s).
function userAction() {
try {
apiCallThatCanThrow();
} catch (err) {
throw new Error('New error message', { cause: err });
}
}
try {
userAction();
} catch (err) {
console.log(err);
console.log(`Cause by: ${err.cause}`);
}
11. Array Find from Last
In the new ECMAScript 2022, there are two new methods: findLast() and findLastIndex(). In the old ECMAScript version, we used the find() and findIndex() methods to find the inside array or string.
const nums = [7, 14, 3, 8, 10, 9];
const lastEven = nums.findLast((num) => num % 2 === 0);
const lastEvenIndex = nums.findLastIndex((num) => num % 2 === 0);
console.log(lastEven); // 10
console.log(lastEvenIndex); // 4
Conclusion
With the newest features of ECMAScript 2022(ES13) brings to JavaScript. Use these features to boost your productivity as a developer and to write cleaner code with greater conciseness and clarity.