วิธีที่ดีที่สุดในปัจจุบัน (ES6+): ใช้ Default Parameters โดยตรงในหัวฟังก์ชัน
ไวยากรณ์
function myFunc(a, b = 0) {
// function body
}
ตัวอย่าง
<html>
<body>
<script>
function inc(val1, inc = 1) {
return val1 + inc;
}
document.write(inc(10, 10)); // 20
document.write("<br>");
document.write(inc(10)); // 11 (ใช้ค่าเริ่มต้น)
</script>
</body>
</html>
ข้อดีของ Default Parameters
- อ่านง่าย ชัดเจน อยู่ที่ Signature <รองรับ Expression:
- รองรับ Destructuring:
function foo({x = 1, y = 2} = {}) - ทำงานกับ
argumentsobject ได้ถูกต้อง (Strict Mode) - ไม่ต้องเช็ค
undefinedเอง
b = computeDefault()
เปรียบเทียบวิธีเก่า
| วิธี | โค้ด | ข้อเสีย |
|---|---|---|
| Default Parameters (ES6) | function(a, b = 1) | - |
| Logical OR | b = b || 1 | 0, "", false, null จะถูกแทนด้วย 1 (Bug) |
| Ternary | b = (b !== undefined) ? b : 1 | Verbose, ต้องเขียนซ้ำ |
| arguments.length | if (arguments.length < 2) b = 1; | ไม่ทำงานใน Arrow Functions, Strict Mode |
Advanced Patterns
// Required Parameter (บังคับส่ง)
const required = () => { throw new Error("Missing parameter"); };
function foo(must = required(), optional = "default") { ... }
// Options Object (หลาย Optional Params)
function fetchData({ url, method = "GET", headers = {}, timeout = 5000 } = {}) { ... }
// Destructuring with Defaults
function connect({ host = "localhost", port = 3000 } = {}) { ... }
สรุป: ใช้ Default Parameters เป็นหลัก ร่วมกับ Options Object สำหรับฟังก์ชันที่มี Optional Parameters มาก