A Recap of Upcoming Features in ECMAScript 2022 (ES13)

A Recap of Upcoming Features in ECMAScript 2022 (ES13)

Daily short news for you
  • Zod 4 has just been introduced with numerous performance improvements. For those who don't know, Zod is a data validation library focused on performance and a developer-friendly API.

    A quick look reveals speed increases of x7, x9, x17, x100... compared to the previous version 😅

    » Read more
  • Revealing how readers of 2coffee.dev will read articles in the future 🫣

    » Read more
  • Microsoft has decided to "transform" the Windows Subsystem for Linux (WSL) on Windows into an open-source project 👏

    Back when I was still into gaming on the computer, I absolutely hated Ubuntu. Probably because it couldn't run games. But programming with Linux kernels was such a delight. So I found myself in a dilemma. I wanted to use Linux but had to stick with Windows.

    Microsoft's release of WSL was like a necessary savior. Quite cool. It's simply using Linux commands on Windows. However, it's still not entirely "smooth" like a real operating system. Now that they’ve open-sourced it, I hope there will be even more improvements 🙏

    microsoft/WSL

    » Read more

As promised since 2016, ECMAScript has committed to releasing a new version of JavaScript every year, with improvements and new features. It's now 2022, so what are the upcoming features? Let's recap some of the highlights.

Private slots

JavaScript has long supported Class syntax, but there are still some shortcomings. One of the features in ES13 is the introduction of private slots in Classes.

class Person {
  #name;

  getName() {
      return this.#name;
  }

  setName(name) {
      this.#name = name;
  }
}

With private slots, you can no longer access the name property directly; instead, you must use get/set methods.

const p = new Person();
p.setName('2coffee.dev');
p.name; // undefined
p.getName(); // 2coffee.dev

Additionally, you can use the Object.hasOwn function to determine if a Class contains a specific private property.

Object.hasOwn(Person, 'name'); // true

Top-level await

Previously, if you wanted to use await, you had to use it within an async function. Now, you can use await at the top level, outside of an async function.

async function fetchData() {
  const resp = await fetch('https://jsonplaceholder.typicode.com/users');
  return resp.json();
}
fetchData();

# Now, you can do
const resp = await fetch('https://jsonplaceholder.typicode.com/users');
resp.json();

This feature is also useful with the import syntax. As we know, import is executed asynchronously to make module loading faster. However, it requires writing additional code to wait for the module to be loaded and ready to use its functions. With ES13, the import syntax will work "as if" it's synchronous by using Promise.all for all imports.

Let's assume two modules, first.mjs and second.mjs, export asynchronous functions:

# first.mjs
async function first() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('first');
    }, 1000);
  });
}

export default first();

Then, use these modules:

import { first } from './first.mjs';
import { second } from './second.mjs';
console.log(first, second);

# will be equivalent to
import { promise as firstPromise, first } from './first.mjs';
import { promise as secondPromise, second } from './second.mjs';
export const promise = (async () => {
  await Promise.all([firstPromise, secondPromise]);
  console.log(first, second);
})();

Error Cause

Error cause is a new approach to error handling in JavaScript. Consider the following code snippet for fetching data:

const fetchData = async () => {
  return await fetch(url)
    .catch(err => {
        // What will you do with err?  
    });
}

What will you do with err? Will you log it and throw a new error message saying "Failed to fetch data"?

const fetchData = async () => {
  return await fetch(url)
    .catch(err => {
        console.log(err);
        throw new Error('Failed to fetch data');
    });
}

When calling fetchData and encountering an error, you will receive new Error('Failed to fetch data') instead of the original err. This makes it challenging to trace the error when using nested catch blocks, as the resultant error message may not be the expected err, but a different error message.

With ES13, you can use Error Cause to throw new Error('Failed to fetch data') while also including the err itself:

const fetchData = async () => {
  return await fetch(url)
    .catch(err => {
        throw new Error('Failed to fetch data', { cause: err });
    });
}

You can then access err in fetchData as follows:

try {
  resp = await fetchData();
  // ...  
} catch(e) {
  console.log('cause', e.cause);
}

.at() Method

Use the .at() method to retrieve the element at the specified index. You can also use a negative index to retrieve positions from right to left.

['a', 'b', 'c'].at(0); // a
['a', 'b', 'c'].at(-1); // c

This method applies to both arrays and strings.

RegExp match indices

Add the /d flag to a regex to capture the start and end indices of the matching string. These indices are stored in the indices property.

const matchObj = /(a+)(b+)/d.exec('aaaabb');
console.log(matchObj.indices); // [[0, 6], [0, 4], [4, 6]]

Conclusion

These are some of the highlights of the upcoming features in ECMAScript 2022. ES13 is expected to be released around June 2022. Stay updated!

References:

Premium
Hello

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (2)

Leave a comment...
Avatar
Tiến Đức2 years ago

Chỗ error kia hơi khó hiểu nhỉ

Reply
Avatar
Xuân Hoài Tống2 years ago

B đọc kĩ lại xem chẳng qua là mình có thể "gắn" được error kèm trong lúc trả về error thôi :D

Avatar
Trịnh Thị Anh2 years ago

Có ai đọc mãi mà không hiểu vụ import không ạ? Chắc mỗi t

Reply
Avatar
Xuân Hoài Tống2 years ago

import là một cú pháp nhập một module theo cách bất đồng bộ vào file của bạn, chính vì bất đồng bộ nên trước kia bạn cần phải "chờ" cho mã được import xong hoàn toàn mới bắt đầu dùng được

Avatar
Tùng Nguyễn2 years ago

import chạy bất đồng bộ, h c dùng await vào thì nó sẽ đồng bộ kiểu thế