JavaScript ES6+: Arrow Functions và Destructuring
Arrow Functions
Cú pháp cũ
function add(a, b) {
return a + b;
}
// Anonymous
setTimeout(function() {
console.log('Hello');
}, 1000);
Arrow function - Ngắn gọn hơn
const add = (a, b) => a + b;
setTimeout(() => console.log('Hello'), 1000);
Lưu ý về 'this'
Arrow function không bind this của riêng nó → rất hữu ích trong callback.
Destructuring
Object destructuring
const user = { name: 'Hân', age: 21, major: 'IT' };
// Cũ
const name = user.name;
const age = user.age;
// Mới
const { name, age, major } = user;
Array destructuring
const scores = [95, 88, 92];
// Lấy phần tử đầu và thứ 3
const [first, , third] = scores;
Default values + renaming
const { name: fullName = 'Anonymous', role = 'student' } = user;
Spread & Rest Operator
// Copy array/object
const newArray = [...oldArray];
const newObj = { ...oldObj, newProp: 'value' };
// Rest parameters
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
Let vs Const vs Var
var: function scope, hoisting → dễ buglet: block scope, không hoistingconst: block scope, không reassign (nhưng object properties có thể thay đổi)
Rule: Dùng const mặc định, chỉ dùng let khi cần reassign.
Kết luận
ES6+ giúp code JavaScript:
- Ngắn gọn hơn
- Dễ đọc hơn
- Ít bug hơn
- Hiện đại hơn
Hãy luôn dùng ES6+ trong mọi project mới!
