Destructuring cho phép trích xuất thuộc tính đối tượng ngay trong tham số hàm. Cú pháp: function fn({ prop1, prop2 = defaultValue }) {...}. Giúp code ngắn gọn, rõ ràng.
Ví dụ
Hàm add nhận đối tượng và phân rã các thuộc tính a, b, c, d với giá trị mặc định 0:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Destructuring tham số hàm</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.sample, .result { font-size: 18px; font-weight: 500; color: red; }
.result { color: rebeccapurple; }
</style>
</head>
<body>
<h1>Phân rã tham số hàm trong JavaScript</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">THỰC HIỆN</button>
<h3>Nhấn nút để gọi hàm add() với đối tượng {a:22, b:44, c:55, d:99}</h3>
<script>
const sampleEle = document.querySelector(".sample");
const resultEle = document.querySelector(".result");
sampleEle.textContent = "{a:22, b:44, c:55, d:99}";
function add({ a = 0, b = 0, c = 0, d = 0 }) {
return a + b + c + d;
}
document.querySelector(".Btn").addEventListener("click", () => {
resultEle.innerHTML += `Tổng = ${add({ a: 22, b: 44, c: 55, d: 99 })}`;
});
</script>
</body>
</html>
Kết quả
Kết quả: Tổng = 220 (22+44+55+99).
Ưu điểm: Tự động gán mặc định, bỏ qua thuộc tính thừa, code tự mô tả (self-documenting).