Discover the Top 5 Exciting Features of ES13 You Must Know
Written on
Chapter 1: Introduction to ES13
ECMAScript 2022 (ES13) has been around for some time, introducing an array of beneficial features. In this article, I'll share five standout techniques that I've started using in my projects.
Section 1.1: Top-Level Await
One of my favorite additions is the top-level await feature, which significantly enhances code readability and elegance by eliminating callback hell.
Old Approach:
const getUserInfoOld = () => {
return fetch('/getUserId')
.then((userId) => {
return fetch('/getUserInfo', { body: JSON.stringify({ userId }) })
.then((userInfo) => userInfo);});
}
Using Await:
const getUserInfo = async () => {
const userId = await fetch('/getUserId');
const userInfo = await fetch('/getUserInfo', {
body: JSON.stringify({ userId })});
return userInfo;
}
The "async" keyword isn't the only context where you can utilize "await"; it can also be applied in various other scenarios.
const mockUserInfo = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ userName: 'fatfish' });}, 1000);
});
}
const userInfo = await mockUserInfo();
console.log(userInfo); // Outputs: { userName: 'fatfish' }
This feature unlocks numerous possibilities that were previously unattainable. You can dynamically load modules, initialize databases, and conditionally render modules, as shown below:
const enStrings = await import(/i18n/en);
const connection = await connectDB();
const showBlackTheme = window.location.search.includes('theme=black');
if (showBlackTheme) {
await import('/theme/black.js');
} else {
await import('/theme/white.js');
}
The first video titled "ECMAScript 2022: New Exciting JavaScript Features" delves into the highlights of ES13, showcasing its innovative capabilities.
Section 1.2: Object.hasOwn
Determining if a property exists on an object is a common requirement. Traditionally, developers have relied on the "in" operator or obj.hasOwnProperty. However, both methods have inherent limitations.
Using the "in" Operator:
const Person = function (age) {
this.age = age;
}
Person.prototype.name = 'fatfish';
const p1 = new Person(24);
console.log('age' in p1); // true
console.log('name' in p1); // true
Using hasOwnProperty:
console.log(p1.hasOwnProperty('age')); // true
console.log(p1.hasOwnProperty('name')); // false
While hasOwnProperty helps filter out prototype properties, it can still lead to errors in certain cases.
Object.create(null).hasOwnProperty('name'); // Throws TypeError
The new Object.hasOwn method provides a safer, more convenient alternative, as seen below:
let object = { age: 24 };
Object.hasOwn(object, 'age'); // true
let object2 = Object.create({ age: 24 });
Object.hasOwn(object2, 'age'); // false
let object3 = Object.create(null);
Object.hasOwn(object3, 'age'); // false
Section 1.3: The .at() Method for Arrays
To access elements from the end of an array, one typically uses array.length - 1.
const array = [1, 2, 3, 4, 5];
const lastEle = array[array.length - 1]; // 5
However, ES2022 introduces the .at() method, which improves code clarity by allowing both positive and negative indices.
const lastEle = array.at(-1); // 5
const firstEle = array.at(0); // 1
Section 1.4: Error Cause Specification
With the new ES2022 specification, the new Error() constructor can now have a cause specified for the error, enhancing error handling.
const readFiles = (filePaths) => {
return filePaths.map((filePath) => {
try {
// Code to read files} catch (error) {
throw new Error(${filePath} error, { cause: error });}
});
}
Section 1.5: Private Slots and Methods
Historically, developers used underscores to denote private properties, but this method is insecure, as properties can still be modified externally.
class Person {
constructor(name) {
this._money = 1;
this.name = name;
}
get money() {
return this._money;}
set money(money) {
this._money = money;}
showMoney() {
console.log(this._money);}
}
With ES2022, we can use # to create secure private properties.
class Person {
#money = 1;
constructor(name) {
this.name = name;}
get money() {
return this.#money;}
set money(money) {
this.#money = money;}
showMoney() {
console.log(this.#money);}
}
You can’t access #money directly from outside the class, ensuring its privacy.
The second video, "Amazing New JavaScript Features in ECMAScript 2022 (ES13)," offers insights into these exciting advancements.
Finally, thank you for reading! I hope you continue to follow my work for more insightful content.