Các tính năng mới trong ES2023 mà bạn nên biết
Khám phá những tính năng JavaScript mới nhất trong phiên bản ES2023 và cách áp dụng chúng vào dự án thực tế
ES2023 (ECMAScript 2023) đã được release với nhiều tính năng mới thú vị giúp JavaScript trở nên mạnh mẽ và linh hoạt hơn. Trong bài viết này, chúng ta sẽ cùng khám phá những tính năng quan trọng nhất mà bạn nên biết.
1. Array.prototype.toSorted()
Phương thức mới này tương tự như sort() nhưng không thay đổi mảng gốc, thay vào đó trả về một mảng mới đã được sắp xếp.
const numbers = [3, 1, 4, 1, 5, 9, 2];
// Cách cũ (mutating)
const sorted1 = [...numbers].sort(); // [1, 1, 2, 3, 4, 5, 9]
// Cách mới (non-mutating)
const sorted2 = numbers.toSorted(); // [1, 1, 2, 3, 4, 5, 9]
console.log(numbers); // [3, 1, 4, 1, 5, 9, 2] - không thay đổi
Với custom comparator
const users = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 }
];
const sortedByAge = users.toSorted((a, b) => a.age - b.age);
console.log(sortedByAge);
// [{ name: 'Bob', age: 25 }, { name: 'Alice', age: 30 }, { name: 'Charlie', age: 35 }]
2. Array.prototype.toReversed()
Tương tự như reverse() nhưng không thay đổi mảng gốc:
const letters = ['a', 'b', 'c', 'd'];
const reversed = letters.toReversed(); // ['d', 'c', 'b', 'a']
console.log(letters); // ['a', 'b', 'c', 'd'] - không thay đổi
3. Array.prototype.with()
Phương thức này cho phép thay thế một phần tử tại index cụ thể mà không thay đổi mảng gốc:
const fruits = ['apple', 'banana', 'orange'];
const newFruits = fruits.with(1, 'grape');
console.log(newFruits); // ['apple', 'grape', 'orange']
console.log(fruits); // ['apple', 'banana', 'orange'] - không thay đổi
Ứng dụng với React state
// Trong React component
const [items, setItems] = useState(['item1', 'item2', 'item3']);
const updateItem = (index, newValue) => {
setItems(prev => prev.with(index, newValue));
};
4. Array.prototype.toSpliced()
Phiên bản non-mutating của phương thức splice():
const colors = ['red', 'green', 'blue', 'yellow'];
// Xóa 1 phần tử từ index 1, thêm 2 phần tử mới
const newColors = colors.toSpliced(1, 1, 'purple', 'pink');
console.log(newColors); // ['red', 'purple', 'pink', 'blue', 'yellow']
console.log(colors); // ['red', 'green', 'blue', 'yellow'] - không thay đổi
5. Array.prototype.findLast() và findLastIndex()
Tìm phần tử cuối cùng thỏa mãn điều kiện:
const numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const lastEven = numbers.findLast(n => n % 2 === 0); // 2
const lastEvenIndex = numbers.findLastIndex(n => n % 2 === 0); // 7
// Ứng dụng thực tế
const logs = [
{ level: 'info', message: 'Started', timestamp: 1 },
{ level: 'error', message: 'Failed', timestamp: 2 },
{ level: 'info', message: 'Retrying', timestamp: 3 },
{ level: 'error', message: 'Critical', timestamp: 4 }
];
const lastError = logs.findLast(log => log.level === 'error');
console.log(lastError); // { level: 'error', message: 'Critical', timestamp: 4 }
6. Hashbang Grammar
ES2023 chính thức hỗ trợ hashbang (#!) ở đầu file để chạy trực tiếp:
#!/usr/bin/env node
console.log('Hello from ES2023!');
7. WeakMap và WeakSet keys từ symbols
Giờ đây có thể sử dụng symbols làm keys cho WeakMap:
const wm = new WeakMap();
const key = Symbol('key');
const obj = {};
wm.set(key, 'value');
console.log(wm.get(key)); // 'value'
Ứng dụng thực tế
Immutable data updates
class TodoList {
constructor(items = []) {
this.items = items;
}
addItem(item) {
return new TodoList([...this.items, item]);
}
updateItem(index, newItem) {
return new TodoList(this.items.with(index, newItem));
}
removeItem(index) {
return new TodoList(this.items.toSpliced(index, 1));
}
sortItems() {
return new TodoList(this.items.toSorted((a, b) => a.priority - b.priority));
}
}
// Sử dụng
const todos = new TodoList([
{ text: 'Learn ES2023', priority: 1 },
{ text: 'Build app', priority: 3 },
{ text: 'Write tests', priority: 2 }
]);
const sortedTodos = todos.sortItems();
const updatedTodos = sortedTodos.updateItem(0, { text: 'Master ES2023', priority: 1 });
Functional programming helpers
const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);
const processArray = pipe(
arr => arr.toSorted((a, b) => b - a), // Sort descending
arr => arr.toSpliced(0, 0, 999), // Add 999 at beginning
arr => arr.with(-1, 0) // Replace last element with 0
);
const result = processArray([3, 1, 4, 1, 5]);
console.log(result); // [999, 5, 4, 3, 1, 0]
Browser Support
Các tính năng ES2023 đã được hỗ trợ trong:
- Chrome: 110+
- Firefox: 115+
- Safari: 16+
- Node.js: 20+
Sử dụng với Babel
// .babelrc
{
"presets": [
["@babel/preset-env", {
"targets": {
"browsers": ["last 2 versions"]
}
}]
]
}
Kết luận
ES2023 mang đến nhiều tính năng hữu ích giúp code JavaScript trở nên clean và functional hơn. Những phương thức array mới đặc biệt quan trọng trong việc xây dựng ứng dụng với immutable data patterns.
Những lợi ích chính:
- Immutability: Tránh side effects không mong muốn
- Functional programming: Code dễ đọc và test hơn
- Performance: Tối ưu hơn trong một số trường hợp
- Developer experience: Syntax ngắn gọn và rõ ràng
Hãy bắt đầu áp dụng những tính năng này vào dự án của bạn để trải nghiệm sức mạnh của JavaScript hiện đại!
Công cụ dùng kèm bài này
Dũng QB
Lập trình viên fullstack ở Sài Gòn, viết code từ 2014. Chủ yếu viết phần mềm cho người làm marketing và bán hàng trên Facebook, TikTok, Telegram.
Về mìnhBình luận
Chưa có bình luận nào. Bạn là người đầu tiên.