What are the new features in ES2022?


ECMA Script 2022, which is due to be released soon, will be popular in some months. Let's have a look at some of the capabilities ES2022, so we can be a part of it.

Features of ES2022

1. Method  .at()  of indexable values.

 You can read detail about a given index with this feature. it can take delivery of poor indexes to examine elements from the give up of the given datatype. 

For example

[1,2,3,4,5].at(3)  // returns 4[1,2,3,4,5].at(-2)   // returns 4

Datatypes supporting this function.

  • String
  • Array
  • All Typed Array classes: Uint8Array etc.

2. RegExp match indices

Adding a flag /d to an everyday expression produces suit objects that document the start and give up of every organization capture.

There are different ways to match indexes

  • Match indices for numbered group
const matchObj = /(y+)(z+)/d.exec('yyyyzz');console.log(matchObj);
/*
Output -
['yyyyzz', 'yyyy', 'zz', index: 0, input: 'yyyyzz', groups: undefined, indices: Array(3)]
*/

Because of the ordinary expression flag /d, matchObj additionally has assets .indices that statistics for every numbered group wherein it become captured within the input string.

matchObj.indices[1];
/*
Output -
[0, 4]
*/

Match indices for named groups

const matchObj = /(?<ys>a+)(?<zs>b+)/d.exec('yyyyzz');console.log(matchObj);
/*
Output -
['yyyyzz', 'yyyy', 'zz', index: 0, input: 'yyyyzz', groups: {ys: 'yyyy', zs: 'zz'}, indices: Array(3)]
*/

Their indices are stored in  matchObj.indices.groups

matchObj.indices.groups;
/*
Output -
{ ys: [0,4], zs: [4,6] }
*/

3.  Object.hasOwn(obj, propKey)

It is a safe and best way to check that  propKey  is the own property of  obj  the object. It is similar to  Object.prototype.hasOwnProperty  but it supports all object types.

const proto = {
protoProp: 'protoProp',
};
const obj = {
__proto__: proto,
objProp: 'objProp',
};
console.log('protoProp' in obj); // output - true.
console.log(Object.hasOwn(obj, 'protoProp')) // output - false
console.log(Object.hasOwn(proto, 'protoProp')); // output - true.

4.  error.cause

Errors and it’s subclasses now let us specify the motive in the back of the mistake. that is beneficial in deeply nested features wherein we’ve chained errors blocks to speedy find the error.

function readFiles(filePaths) {
return filePaths.map(
(filePath) => {
try {
// ···
} catch (error) {
throw new Error(
`While processing ${filePath}`,
{cause: error}
);
}
});
}

5. Top-level await modules

We can now use wait for at the top levels of modules and don’t need to input async functions or methods anymore.

Loading modules dynamically

const messages = await import(`./messages-${language}.mjs`);

Using a fallback if module loading fails

let lodash;
try {
lodash = await import('https://primary.example.com/lodash');
} catch {
lodash = await import('https://secondary.example.com/lodash');
}

Using whichever resource loads fastest

const resource = await Promise.any([
fetch('http://example.com/first.txt')
.then(response => response.text()),
fetch('http://example.com/second.txt')
.then(response => response.text()),
]);

6. New members of classes

Public properties can be created via

Instance public fields

class InstPublicClass {
// Instance public field
instancePublicField = 0; // (A)
constructor(value) {
// We don’t need to mention .property elsewhere!
this.property = value; // (B)
}
}
const inst = new InstPublicClass('constrArg');

Static public fields

const computedFieldKey = Symbol('computedFieldKey');
class StaticPublicFieldClass {
static identifierFieldKey = 1;
static 'quoted field key' = 2;
static [computedFieldKey] = 3;
}
console.log(StaticPublicFieldClass.identifierFieldKey) //output -> 1
console.log(StaticPublicFieldClass['quoted field key']) //output -> 2
console.log(StaticPublicFieldClass[computedFieldKey]) //output -> 3

Private slots are new and can be created via

Instance private fields

class InstPrivateClass {
#privateField1 = 'private field 1'; // (A)
#privateField2; // (B) required!
constructor(value) {
this.#privateField2 = value; // (C)
}
/**
* Private fields are not accessible outside the class body.
*/
checkPrivateValues() {
console.log(this.#privateField1); // output -> 'private field 1'
console.log(this.#privateField2); // output -> 'constructor argument'
}
}
const inst = new InstPrivateClass('constructor argument');
inst.checkPrivateValues();
console.log("inst", Object.keys(inst).length === 0) //output -> inst, true

Instance and static private fields

class InstPrivateClass {
#privateField1 = 'private field 1'; // (A)
#privateField2; // (B) required!
static #staticPrivateField = 'hello';
constructor(value) {
this.#privateField2 = value; // (C)
}
/**
* Private fields are not accessible outside the class body.
*/
checkPrivateValues() {
console.log(this.#privateField1); // output -> 'private field 1'
console.log(this.#privateField2); // output -> 'constructor argument'
} static #twice() {
return this.#staticPrivateField + " " + this.#staticPrivateField;
}
static getResultTwice() {
return this.#twice()
}
}
const inst = new InstPrivateClass('constructor argument');
inst.checkPrivateValues();
console.log("inst", Object.keys(inst).length === 0) //output -> "inst", true
console.log(InstPrivateClass.getResultTwice()); // output -> "hello hello"

Private methods and accessors

class MyClass {
#privateMethod() {}
static check() {
const inst = new MyClass();
console.log(#privateMethod in inst) // output-> true console.log(#privateMethod in MyClass.prototype) // output-> false console.log(#privateMethod in MyClass) // output-> false
}
}
MyClass.check();

Static initialization blocks in classes. For static facts, we’ve got Static fields and Static Blocks that can be performed whilst elegance is created.

class Translator {
static translations = {
yes: 'ya',
no: 'nai',
maybe: 'vielleicht',
};
static englishWords = [];
static germanWords = [];
static { // (A)
for (const [english, german] of Object.entries(this.translations)) {
this.englishWords.push(english);
this.germanWords.push(german);
}
}
}
console.log(Translator.englishWords, Translator.germanWords)
//Output -> ["yes", "no", "maybe"], ["ya", "nai", "vielleicht"]
  • Private slot checks — This functionality helps you to check that the object has the given private slot in it.
class C1 {
#priv() {}
static check(obj) {
return #priv in obj;
}
}
console.log(C1.check(new C1())) // output true

These awesome functions will help us to beautify our tasks and enhance our coding strategies. I’m truly excited to strive these features out in my challenge.

I hope you like these amazing ES2022 Features and this article will help you to update JS.

*

Post a Comment (0)
Previous Post Next Post