ES10 Interactive Hub — ECMAScript 2019
Quality-of-life upgrades: Array.flat/flatMap, Object.fromEntries, optional catch binding, trimStart/trimEnd, stable Array.sort, Symbol.description — nhiều convenience method cho daily coding.
Array.flat() & flatMap()
Chuyên đề cốt lõi
💡 Khái niệm tóm tắt
flat() làm phẳng mảng lồng (nested), flatMap() kết hợp map + flat 1 cấp trong 1 lượt duyệt.
🤔 Tại sao cần tính năng này?
Trước ES10, để làm phẳng mảng phải dùng reduce + concat hoặc spread cồng kềnh. Đặc biệt khi map mà output là mảng (vd tách câu thành từ), kết quả ra mảng 2 chiều, phải gọi flat thêm 1 lần.
// Trước ES10 — flatten thủ công
var nested = [1, [2, 3], [4, [5, 6]]];
var flat = nested.reduce(function(acc, val) {
return acc.concat(val);
}, []);
console.log(flat); // [1, 2, 3, 4, [5, 6]] (chỉ 1 cấp)
// map mà output là mảng → cần flatten
var sentences = ['hello world', 'goodbye'];
var words = sentences.map(function(s) { return s.split(' '); });
console.log(words); // [['hello','world'], ['goodbye']]// ES10 — flat() với tham số depth
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]]
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6]
console.log(nested.flat(Infinity)); // làm phẳng vô hạn cấp
// flatMap — map + flat 1 cấp
const sentences = ['hello world', 'goodbye'];
const words = sentences.flatMap(s => s.split(' '));
console.log(words); // ['hello', 'world', 'goodbye']Bảng Tra Cứu Nhanh ES10
Xem nhanh cấu trúc + copy snippet
flat() làm phẳng mảng lồng (nested), flatMap() kết hợp map + flat 1 cấp trong 1 lượt duyệt.
const nested = [1, [2, 3], [4, [5, 6]]]; console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]] console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6] ...
Hàm ngược của Object.entries() — convert mảng các cặp [key, value] thành object.
const user = { name: 'Lan', age: 25, password: 'secret' };
const safe = Object.fromEntries(
Object.entries(user).filter(([k]) => k !== 'password')
...Cho phép bỏ qua biến error trong catch khi bạn không cần dùng tới nó — code gọn hơn.
function safeParse(str) {
try {
return JSON.parse(str);
...Xóa khoảng trắng (whitespace) chỉ ở đầu hoặc chỉ ở cuối chuỗi — bổ sung cho trim() chuẩn ES5.
const str = " Xin chào ";
console.log(`[${str.trimStart()}]`); // [Xin chào ]
console.log(`[${str.trimEnd()}]`); // [ Xin chào]
...ES10 chính thức yêu cầu Array.prototype.sort phải STABLE — các phần tử bằng nhau (theo comparator) giữ nguyên thứ tự xuất hiện ban đầu.
const users = [
{ name: "An", age: 25 },
{ name: "Bình", age: 25 },
...Property "description" cho phép đọc thẳng chuỗi mô tả của Symbol thay vì phải hack qua String(sym).slice().
const sym = Symbol("userId");
console.log(sym.description); // 'userId'
const anon = Symbol();
...