The ES2020 features
by aaronchenwei
Private variable in Class
class MyClass {
#privateVariable = "Hello private world";
helloWorld() {
console.info(this.#privateVariable);
}
}
const myClass = new MyClass();
myClass.helloWorld(); // works
console.info(myClass.#helloWorld); // SyntaxError: Private field '#helloWorld' must be declared in an enclosing class
BigInt
const maxInteger = Number.MAX_SAFE_INTEGER;
console.info(maxInteger); // 9007199254740991
console.info(maxInteger + 1); // 9007199254740992
console.info(maxInteger + 2); // 9007199254740992 ??
console.info(maxInteger + 3); // 9007199254740994
console.info(maxInteger + 200); // 9007199254741192 ??
console.info(maxInteger * 200); // 1801439850948198100 ??
Promise.allSettled()
const resolvingPromise1000ms = new Promise((resolve, reject) =>
setTimeout(resolve, 1000)
);
const rejectingPromise2000ms = new Promise((resolve, reject) =>
setTimeout(reject, 2000)
);
const timeCheckpoint = Date.now();
Promise.allSettled([resolvingPromise1000ms, rejectingPromise2000ms]).then(
(data) => {
const elapsedTimeInMS = Date.now() - timeCheckpoint;
console.info(`Promise.allSettled resolved after ${elapsedTimeInMS}ms`);
console.info(data);
}
);
/*
Promise.allSettled resolved after 2006ms // ? not sure why we have 6ms
[
{ status: 'fulfilled', value: undefined },
{ status: 'rejected', reason: undefined }
]
*/
Nullish Coalescing Operator
let object = {
car: {
speed: 0,
name: "",
},
};
console.info(object.car.speed || 90); // 90
console.info(object.car.speed ?? 90); // 0
console.info(null || true); // true
console.info(null ?? true); // true
console.info(undefined || true); // true
console.info(undefined ?? true); // true
console.info(0 || true); // true
console.info(0 ?? true); // 0
console.info("" || true); // true
console.info("" ?? true); // ""
console.info([] || true); // []
console.info([] ?? true); // []
console.info({} || true); // {}
console.info({} ?? true); // {}
console.info(true || "hey"); // true
console.info(true ?? "hey"); // true
console.info(false || true); // true
console.info(false ?? true); // false
Optional Chaining Operator
let person = {
name: "John",
age: 20,
};
if (person.city !== undefined && person.city.locale !== undefined) {
const cityLocale = person.city.locale;
}
console.info(person?.city?.locale);
Dynamic Import
print.js
const print = (value) => console.info(value);
export { print };
const doPrint = async (value) => {
const Print = await import("./print.js");
Print.print(value);
};
doPrint("Dynamic import works !");
String.prototype.matchAll
const re = /(Mister )\w+/g;
const str = "Mister Smith with Mister Galladon";
const matches = str.matchAll(re);
console.info(matches); // Object [RegExp String Iterator] {}
console.info(Array.from(matches));
/*
[
[
'Mister Smith',
'Mister ',
index: 0,
input: 'Mister Smith with Mister Galladon',
groups: undefined
],
[
'Mister Galladon',
'Mister ',
index: 18,
input: 'Mister Smith with Mister Galladon',
groups: undefined
]
]
*/