Function Expression vs Function Declaration
Function Expression: Hàm được tạo như một **giá trị (expression)**, gán cho biến. Không bị hoisted.
Function Declaration: Khai báo hàm với từ khóa function ở đầu statement. Bị hoisted.
Ví dụ minh họa
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Function Expression</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 18px; font-weight: 500; color: rebeccapurple; font-family: monospace; }
button { padding: 8px 16px; cursor: pointer; }
</style>
</head>
<body>
<h1>Function Expression trong JavaScript</h1>
<div class="result"></div>
<button class="btn-demo">HIỂN THỊ FUNCTION EXPRESSION</button>
<h3>Nhấn nút để xem function expression</h3>
<script>
const resultEle = document.querySelector(".result");
const btn = document.querySelector(".btn-demo");
// Function Expression: gán hàm cho biến
const a = function() {
return "Đây là function expression";
};
btn.addEventListener("click", () => {
// a là function object
resultEle.textContent = "a = " + a + "\n";
// a() gọi hàm
resultEle.textContent += "a() = " + a() + "\n";
// So sánh với Function Declaration
resultEle.textContent += "\n--- So sánh ---\n";
resultEle.textContent += "Function Declaration: bị hoisted, gọi được trước khi khai báo\n";
resultEle.textContent += "Function Expression: KHÔNG hoisted, phải khai báo trước khi gọi";
});
</script>
</body>
</html>
Các loại Function Expression
1. Anonymous Function Expression (Ẩn danh)
const greet = function(name) {
return 'Hello ' + name;
};
2. Named Function Expression (Có tên)
const factorial = function fact(n) {
if (n <= 1) return 1;
return n * fact(n - 1); // Đệ quy dùng tên nội bộ 'fact'
};
// fact chỉ tồn tại trong scope của hàm
3. Arrow Function Expression (ES6)
const add = (a, b) => a + b;
const greet = name => `Hello ${name}`;
const noArg = () => 'No args';
So sánh chi tiết
| Đặc điểm | Function Declaration | Function Expression |
|---|---|---|
| Cú pháp | function foo() {} | const foo = function() {} |
| Hoisting | ✓ Toàn bộ hàm | ✗ Chỉ biến (let/const: TDZ) |
| Gọi trước khai báo | OK | Lỗi (ReferenceError/TypeError) |
| this binding | Dynamic (tùy cách gọi) | Dynamic (tương tự) |
| Arrow function | Không có | Có (lexical this) |
| Dùng làm callback | Ít dùng | Rất phổ biến |
IIFE - Immediately Invoked Function Expression
// Tạo scope riêng, chạy ngay lập tức
(function() {
const private = 'secret';
console.log(private);
})();
// ES6: dùng block + let/const
{
const private = 'secret';
console.log(private);
}
// Arrow IIFE
(() => {
console.log('Arrow IIFE');
})();
Khi nào dùng Function Expression?
- Callback functions:
arr.map(x => x * 2) - Methods trong object:
const obj = { method() {} } - IIFE tạo scope riêng.
- Conditional function definition.
- Functional programming patterns.