A Recap of Upcoming Features in ECMAScript 2022 (ES13)

A Recap of Upcoming Features in ECMAScript 2022 (ES13)

Daily short news for you
  • There’s another tool to help quickly search command history: atuinsh/atuin.

    What’s interesting is that it uses SQLite for storage. It also provides the feature of completely synchronizing (encrypting) history between machines. How cool is that 🤓

    » Read more
  • I am really impressed with the gemma-3n-E4B model from Google. This is one of the promising models that aims to bring large language models to run on mobile devices or the web or embedded...

    It feels like it understands the prompts better, because I’ve tried many low-parameter models that often overlook my prompts. For example, when I say, "Just return the answer, no need for further explanation," many still tend to add introductory phrases or explanations... but with gemma-3n, the responses are very much to the point.

    » Read more
  • Before, we used CSS to create a "loading" effect, but now we can achieve "loading" with just a single SVG file: svg-loaders

    » 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ố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ị 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ễ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ế