ใช้ Default Parameters (ES6) เพื่อกำหนดค่าเริ่มต้นและตรวจสอบว่ามีการส่ง argument มาหรือไม่
ตัวอย่างจากบทความ
<!DOCTYPE html>
<html>
<body>
<script>
function display(arg1 = 'Tutorials', arg2 = 'Learning') {
document.write(arg1 + ' ' + arg2 + "<br>");
}
display('Tutorials', 'Learning'); // ส่งครบ 2 ค่า
display('Tutorials'); // ส่ง 1 ค่า arg2 ใช้ default
display(); // ไม่ส่ง ใช้ default ทั้งคู่
</script>
</body>
</html>
วิธีตรวจสอบแบบต่างๆ
1. Default Parameters (ES6 - แนะนำ)
function foo(a = 'default', b = 'default') {
console.log(a, b);
}
foo(); // 'default' 'default'
foo('hello'); // 'hello' 'default'
foo('hello', 'world'); // 'hello' 'world'
2. ตรวจสอบด้วย arguments.length (ES5)
function legacyCheck(a, b) {
if (arguments.length < 2) {
console.log('Missing arguments');
}
console.log('a:', a, 'b:', b);
}
3. ตรวจสอบ undefined โดยตรง
function checkExplicit(a, b) {
if (b === undefined) {
console.log('b not provided');
b = 'default';
}
}
4. ใช้ Rest Parameters (ES6)
function flexible(...args) {
console.log('Received:', args.length, 'arguments');
console.log(args);
}
flexible(); // 0
flexible(1); // 1
flexible(1, 2, 3); // 3
ความแตกต่าง: ไม่ส่ง vs ส่ง undefined
function test(a = 'default') {
console.log(a);
}
test(); // 'default' (ไม่ส่ง)
test(undefined); // 'default' (ส่ง undefined - default ทำงาน)
test(null); // null (ส่ง null - default ไม่ทำงาน!)
สำคัญ: Default parameter ทำงาน רקเมื่อค่าเป็นundefined(ไม่ได้ส่ง หรือ ส่ง undefined ตรงๆ) ไม่ทำงานกับnull
Pattern: Required Parameter
function required(name) {
if (name === undefined) {
throw new Error('name is required');
}
}
// หรือใช้ default ที่โยน error
function requiredParam(paramName) {
throw new Error(`${paramName} is required`);
}
function createUser(name = requiredParam('name'), age = 18) {
return { name, age };
}