ES11 Interactive Hub — ECMAScript 2020
Tệp đại nhất cho daily coding: optional chaining (?.), nullish coalescing (??), BigInt, dynamic import, Promise.allSettled, globalThis. Mọi modern codebase đều dùng.
Optional chaining (?.)
Chuyên đề cốt lõi
💡 Khái niệm tóm tắt
Truy cập nested property an toàn — tự động trả về undefined nếu chuỗi truy cập gặp null/undefined giữa chừng.
🤔 Tại sao cần tính năng này?
Truy cập dữ liệu lồng nhau từ API thường gặp giá trị null/undefined ở giữa chain, gây "TypeError: Cannot read property of undefined". Phải kiểm tra từng cấp với && rất dài. Optional chaining giải quyết bằng 1 ký tự "?.".
// Kiểm tra thủ công trong ES5
var user = { profile: { address: null } };
// Phải check từng cấp
var city = user && user.profile && user.profile.address && user.profile.address.city;
console.log(city); // undefined
// Gọi function cũng phải check
var result = obj && obj.foo && typeof obj.foo === 'function' && obj.foo();// Optional chaining "?." trong ES11
const user = { profile: { address: null } };
const city = user?.profile?.address?.city;
console.log(city); // undefined (an toàn!)
// Gọi function nếu tồn tại
obj?.foo?.(); // không lỗi nếu foo không có
arr?.[0]; // truy cập array element an toàn
obj?.method?.(arg); // gọi method với argument
// Kết hợp nullish coalescing
const name = user?.profile?.name ?? "Khách";Bảng Tra Cứu Nhanh ES11
Xem nhanh cấu trúc + copy snippet
Truy cập nested property an toàn — tự động trả về undefined nếu chuỗi truy cập gặp null/undefined giữa chừng.
const user = { profile: { address: null } };
const city = user?.profile?.address?.city;
console.log(city); // undefined (an toàn!)
...Toán tử "??" cho fallback CHỈ khi giá trị bên trái là null hoặc undefined — khác với || coi tất cả giá trị falsy là fallback.
const count = 0; const fallback1 = count ?? 10; console.log(fallback1); // 0 (đúng!) ...
Kiểu dữ liệu nguyên thủy mới cho số nguyên lớn hơn Number.MAX_SAFE_INTEGER (2^53 - 1).
const big = 9007199254740993n; // hậu tố 'n'
console.log(big); // 9007199254740993n (chính xác!)
const big2 = BigInt("99999999999999999");
...Cú pháp "import()" trông như function, trả về Promise — cho phép lazy-load module theo điều kiện hoặc khi cần.
button.addEventListener('click', async () => {
const { renderChart } = await import('./chart.js');
renderChart(data);
...Đợi tất cả promise kết thúc (dù thành công hay thất bại) và trả về mảng kết quả chi tiết của từng promise.
const results = await Promise.allSettled([
fetch('/a'),
fetch('/b'),
...Tham chiếu chuẩn hóa đến global object — chạy được trong mọi môi trường: Browser (window), Node.js (global), Web Worker (self), Deno.
globalThis.myLib = { version: '1.0' };
console.log(globalThis.myLib);
if (typeof globalThis.fetch === 'undefined') {
...