A Recap of Upcoming Features in ECMAScript 2022 (ES13)

A Recap of Upcoming Features in ECMAScript 2022 (ES13)

Daily short news for you
  • A library brings a lot of motion effects to your website: animejs.com

    Go check it out, scroll a bit and your eyes will be dazzled 😵‍💫

    » Read more
  • A repository that compiles a list of system prompts that have been "leaked" on the Internet. Very useful for anyone researching how to write system prompts. I must say they are quite meticulous 😅

    jujumilk3/leaked-system-prompts

    » Read more
  • For over a week now, I haven't posted anything, not because I have nothing to write about, but because I'm looking for ways to distribute more valuable content in this rapidly exploding AI era.

    As I shared earlier this year, the number of visitors to my blog is gradually declining. When I looked at the statistics, the number of users in the first six months of 2025 has dropped by 30% compared to the same period last year, and by 15% compared to the last six months of 2024. This indicates a reality that users are gradually leaving. What is the reason for this?

    I think the biggest reason is that user habits have changed. They primarily discover the blog through search engines, with Google being the largest. Almost half of the users return to the blog without going through the search step. This is a positive signal, but it's still not enough to increase the number of new users. Not to mention that now, Google has launched the AI Search Labs feature, which means AI displays summarized content when users search, further reducing the likelihood of users accessing the website. Interestingly, when Search Labs was introduced, English articles have taken over the rankings for the most accessed content.

    My articles are usually very long, sometimes reaching up to 2000 words. Writing such an article takes a lot of time. It's normal for many articles to go unread. I know and accept this because not everyone encounters the issues being discussed. For me, writing is a way to cultivate patience and thoughtfulness. Being able to help someone through my writing is a wonderful thing.

    Therefore, I am thinking of focusing on shorter and medium-length content to be able to write more. Long content will only be used when I want to write in detail or delve deeply into a particular topic. So, I am looking for ways to redesign the blog. Everyone, please stay tuned! 😄

    » 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

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click 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 Đức3 years ago

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

Reply
Avatar
Xuân Hoài Tống3 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ị Anh3 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ống3 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ễn3 years ago

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