Destructuring ในพารามิเตอร์ฟังก์ชัน (Parameter Destructuring) ช่วยสกัดค่าจากอ็อบเจกต์หรืออาร์เรย์ที่ส่งเข้ามาโดยตรง ทำให้โค้ดสะอาด ลดการเขียน obj.prop ซ้ำๆ และรองรับค่าเริ่มต้น (default values) ได้
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Destructuring พารามิเตอร์</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>Destructuring พารามิเตอร์ฟังก์ชันใน JavaScript</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">คลิกที่นี่</button>
<h3>กดปุ่มเพื่อเรียกฟังก์ชันพร้อมส่งอ็อบเจกต์</h3>
<script>
const sampleEle = document.querySelector(".sample");
const resultEle = document.querySelector(".result");
sampleEle.textContent = "{ a: 22, b: 44, c: 55, d: 99 }";
// Destructuring พร้อมค่าเริ่มต้น
function add({ a = 0, b = 0, c = 0, d = 0 }) {
return a + b + c + d;
}
document.querySelector(".Btn").addEventListener("click", () => {
resultEle.textContent = "ผลรวม = " + add({ a: 22, b: 44, c: 55, d: 99 });
});
</script>
</body>
</html>
ผลลัพธ์

เมื่อกดปุ่ม "คลิกที่นี่":

รูปแบบต่างๆ ของ Parameter Destructuring
// 1. อ็อบเจกต์พร้อมค่าเริ่มต้น
function greet({ name = "Guest", age = 18 } = {}) {
return `สวัสดี ${name}, อายุ ${age}`;
}
greet(); // "สวัสดี Guest, อายุ 18"
greet({ name: "สมชาย" }); // "สวัสดี สมชาย, อายุ 18"
// 2. เปลี่ยนชื่อตัวแปร
function test({ x: newX, y: newY }) { ... }
// 3. Nested destructuring
function foo({ user: { name, address: { city } } }) { ... }
// 4. อาร์เรย์ destructuring
function sum([a, b, c = 0]) { return a + b + c; }
sum([1, 2]); // 3
// 5. Rest parameter
function collect({ required, ...rest }) { ... }
ข้อดี
- อ่านโค้ดง่ายขึ้น — ดูพารามิเตอร์ทันทีว่าต้องการฟิลด์ไหน
- ไม่ต้องตรวจสอบ
if (obj && obj.prop)ซ้ำๆ - รองรับค่าเริ่มต้นได้โดยตรง
- ทำงานร่วมกับ TypeScript ได้ดี (type inference)
ข้อควรระวัง
- ส่ง
nullหรือundefinedเข้ามาโดยไม่มี= {}จะโยน Error → ควรใส่ default parameter= {}ไว้ที่ฟังก์ชัน - ไม่สามารถใช้
...restกับอ็อบเจกต์ได้ในพารามิเตอร์ (ทำได้แค่ใน body)