Fat arrow function giúp giảm dòng code, cú pháp =>, không cần từ khóa function lặp lại.
Cú pháp
// Một tham số
argument => expression
// Nhiều tham số
(argument1, argument2) => expression
// Khối lệnh (block body) - cần return explicit
(arg1, arg2) => {
const result = arg1 + arg2;
return result;
}
// Không tham số
() => expression
So sánh: Function thường vs Arrow Function
Function truyền thống
var rank = [7, 8, 9];
var display = rank.map(function(num) {
return num * num;
});
Fat Arrow Function
var rank = [7, 8, 9]; var display = rank.map((num) => num * num); // document.write(display) // sửa: display là array, cần join hoặc log console.log(display); // [49, 64, 81]
Arrow function chắc chắn giảm dòng code và dễ đọc cho callback đơn giản.
Đặc điểm quan trọng
| Đặc điểm | Arrow Function | Regular Function |
|---|---|---|
this | Lexical (từ scope cha) | Dynamic (tùy call site) |
arguments | Không có (dùng rest params ...args) | Có |
new | Không thể dùng làm constructor | Có thể |
prototype | Không có | Có |
super | Lexical (từ class cha) | Dynamic |
| Implicit return | Có (expression body) | Không |
Khi nào dùng Arrow Function?
- ✅ Callback:
.map(),.filter(),.reduce(),setTimeout, event handler. - ✅ Utility functions đơn giản:
const add = (a, b) => a + b; - ✅ IIFE:
(() => { ... })(). - ❌ Object method (trừ class field).
- ❌ Constructor/Prototype.
- ❌ Cần
argumentsobject. - ❌ Cần dynamic
this(event handler gắn trực tiếp element).
Implicit Return vs Block Body
// Implicit return (expression body) - ngắn gọn
const double = x => x * 2;
const add = (a, b) => a + b;
// Block body - cần return explicit
const sum = (a, b) => {
const result = a + b;
return result;
};
// Return object literal - cần wrap bằng ()
const createUser = (name, age) => ({ name, age }); // ✅
// const createUser = (name, age) => { name, age }; // ❌ syntax error