ECMAScript 2022 is the going to be released soon. Here are some new features that have been incorporated and could be used in javascript in upcoming time.
Feature added in ECMAScript 2022 are listed below.
- Top-level
await
- Public and private instance fields
- Static members
- Static class initialization blocks
- Error:
.cause
- Array, String, and TypedArray:
.at()
Method - Object:
.hasOwn()
- RegExp: match
.indices
(‘d’ flag)
Top-level await
Before ECMAScript 2022, await
could only be used 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 the await
can be used at the top level of a module and can be super handy when initialising imports and creating fallbacks.
Before ECMAScript 2022, attempt to use await
outside async
block would cause SyntaxError, so many developers used to use IIFE (Immediately Invoked Function Expression) to get around it. Consider following example
await Promise.resolve(console.log('Hello World'));
// This would cause: SyntaxError: await is only valid in async function
// Alternative to fix the problem
(async function() {
await Promise.resolve(console.log('Hello World'));
// Output: Hello World
}());
After addition to this feature, one would be able to use await
on top level in module
await Promise.resolve(console.log('Hello World'));
// → Hello World
Public and private instance fields
With ECMAScript 2022, one can add a instance fields at class level and can also be marked as private. To declare any field as private, one just need to prepand variable name with #
With ECMAScript 2022, variables can be declared at class level instead of requiring a constructor. Consider following example.
class TextBlock {
title = 'Title'
#subject = 'just a test';
}
const tblock = new TextBlock();
tblock.firstName
// Output: undefined
tblock.title
// Output: Title
Using ECMAScript 2022, methods can also be declared as private, just prepend method name with #
. Consider following example
class TextBlock {
#appendText(text){
this.text = this.text + text;
}
}
const tblock = new TextBlock();
tblock.appendText('This should be appended');
// Output: TypeError: tblock.appendText is not a function
Static members
The class fields proposal also introduces static members. These look and work similarly to how they do in Java: if a member has the static keyword modifier, it exists on the class instead of object instances.
Static member can be declared by using static keyword before variable/method name
class TextBlock {
static description = 'This textblock can hold title, subject and textarea';
static introduce(){
return description;
}
}
TextBlock.description
// Output: This textblock can hold title, subject and textarea
TextBlock.config();
// Output: This textblock can hold title, subject and textarea
Note that static private field and methods are also possible
Static initialization blocks
This new feature provides a mechanism for additional static initialization during class definition evaluation.
class TextBlock {
static translations = {
yes: 'ja',
no: 'nein',
maybe: 'vielleicht',
}
static englishCategory = [];
static germanCategory = [];
static {
for (const [english, german] of Object.entries(this.translations)) {
this.englishCategory.push(english);
this.englishCategory.push(german);
}
}
}
TextBlock.englishCategory;
TextBlock.germanCategory;
Error: .cause
With ECMAScript 2022, it allows Error and its subclasses to now specify the reason behind the error. Sometimes, errors are thrown during more deeply nested function calls and would like to attach more information to them.
With this, one can add more intrinsic information for errors. To use this new feature, one should specify the error options as a second parameter, and with the cause key we can pass the error that we want to chain.
const fetchAccounts = async( array ) => {
try {
const accounts = await fetch('https://example.com/accounts');
return accounts;
} catch (error) {
throw new Error('Something went wrong, please try again', { cause: error })
}
}
try{
const accounts = await fetchAccounts();
} catch(error) {
console.log(error);
console.log(error.cause);
}
Method .at() of indexable values (String, Array etc)
Until this point, programmers have asked for the ability to do negative indexing of JS Arrays, as you can do with other programming languages. That is, asking for the ability to write arr[-1] instead of arr[arr.length-1], where negative numbers count backward from the last element.
This year with ECMAScript 2022 we have a big change with a new method that helps programmers with the negative indexing, the .at() method that is supported by Array, String, or TypedArray.
const fruitsArray = ['banana', 'apple', 'orange', 'kiwi'];
console.log(fruitsArray.at(-1))
const fruit = 'kiwi';
console.log(fruit.at(-1))
// Output: i
Note: The
.at()
also accepts positive numbers, so it can be used as another way when indexing is required.
Object: .hasOwn()
We are used to check if an object contains given property using hasOwnProperty
on its prototype.
However with ECMAScript 2022, its has been simplified with just .hasOwn
if (Object.hasOwn(someObject, "example")) {
console.log("someObject has example 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 regx = /a+(?<Z>z)?/d;
const string1 = "baaaxx";
const matches = regx.exec(string1);
matches.indices[0][0] === 1;
matches.indices[0][1] === 5;
Conclusion
JavaScript since es6 or ECMAScript2015 has been gaining a lot of improvement with almost every year release. And it amazes every times
About The Author
I am Pankaj Baagwan, a System Design Architect. A Computer Scientist by heart, process enthusiast, and open source author/contributor/writer. Advocates Karma. Love working with cutting edge, fascinating, open source technologies.
To consult Pankaj Bagwan on System Design, Cyber Security and Application Development, SEO and SMO, please reach out at me[at]bagwanpankaj[dot]com
For promotion/advertisement of your services and products on this blog, please reach out at me[at]bagwanpankaj[dot]com
Stay tuned <3. Signing off for RAAM