A Recap of Upcoming Features in ECMAScript 2022 (ES13)

A Recap of Upcoming Features in ECMAScript 2022 (ES13)

Daily short news for you
  • This opensource helps you quickly create a personal introduction page about yourself (like a CV): self.so

    » Read more
  • Competition in the model race is becoming increasingly fierce, with tech companies not wanting to be left behind. Llama 4 Scout and Llama 4 Maverick are the latest open-source models from Meta, touted for their superior performance, even surpassing the most advanced models like GPT-4.5, Claude Sonnet 3.7, and Gemini 2.0 Pro... However, alongside this, Scout and Maverick are facing criticism over cheating allegations. Should we trust Meta once again? 🤔

    Llama 4 Scandal: Meta’s release of Llama 4 overshadowed by cheating allegations on AI benchmark

    » Read more
  • Today, I accidentally came across the website notes.andymatuschak.org which has a very interesting note-taking method. Clicking on a link opens a new tab next to it. Each time you click, it continues to open. Just like filing cabinets.

    This presentation style is not only easy to follow but also aligns with the flow of thought. It's a pity that I can't find the author of this open-source project. I wonder if there's anything similar out there 🤔

    » 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
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ế
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