ES2022 is gonna be OP.

Akash Pattnaik - Feb 4 '22 - - Dev Community

ECMAscript2022

ECMAScript 2022 is the new JavaScript standard that is going to be released in June 2022. Let’s overview the most important changes that would appear almost certainly in the new release as they reached the 4th stage of TC39 process.

1. .at() method in arrays

Finally! ES2022 will give us a possibility to index array-like objects from the end. That’s a tiny feature, but it improves core readability when dealing with arrays or strings.

before

const array = [1, 2, 3, 4]
array[array.length - 2] // 3
array.slice(-2)[0]    // 3

const string = "1234"
string[string.length - 2] // '3'
string.slice(-2)[0]    // '3'
Enter fullscreen mode Exit fullscreen mode

after

const array = [1, 2, 3, 4]
array.at(-2) // 3

const string= "1234"
string.at(-2) // '3'
Enter fullscreen mode Exit fullscreen mode

2. Error Cause

.cause property on the error object would allow us to specify which error caused the other error. Here you can see an example use of this new feature ->

try {
  doSomethingThatWillThrowAnError() 
} catch (error) {
  throw new Error('I am the result of another error', { cause: error })
}
Enter fullscreen mode Exit fullscreen mode

I couldn’t find any information whether stack trace of error included in cause would be present in the thrown error. Let me know if you find any information about that.

3. Top-level async/await

Now, in ECMAscript 2022, you can do this shit ->

const moduleName = await fetch("https://example.com/some/random/module")
const service = await import(`/dist/modules/${moduleName}.js`)

// --------------
// ----- OR -----
// --------------

const date = new Date()

if(date.getFullYear() === 2022) {
  await require('/newcode-2022-only.js')
} else {
  await require('/legacy-code.js');
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .