Default Parameter (ES6) cho phép khởi tạo tham số với giá trị mặc định nếu không truyền hoặc truyền undefined.
Ví dụ cơ bản
<html>
<body>
<script>
// default inc = 1
function inc(val1, inc = 1) {
return val1 + inc;
}
document.write(inc(10, 10)); // 20
document.write("<br>");
document.write(inc(10)); // 11 (inc mặc định = 1)
</script>
</body>
</html>
Parameters without defaults after default parameters
JS cho phép tham số không có default đứng sau tham số có default (khác Python, C#...). Giá trị undefined được truyền explicit sẽ trigger default.
Ví dụ
<html>
<body>
<script>
function display(val1 = 10, val2) {
return [val1, val2];
}
document.write(display()); // [10, undefined] - val1 default, val2 undefined
document.write(display(20)); // [20, undefined] - val1=20, val2 undefined
document.write(display(1, 2)); // [1, 2]
document.write(display(undefined, 5)); // [10, 5] - undefined trigger default
</script>
</body>
</html>
Tại sao JS cho phép này?
JavaScript không enforce positional-only parameters. undefined explicit = "tôi muốn dùng default". Cho phép skip argument giữa bằng cách truyền undefined:
function config(host = "localhost", port = 8080, protocol = "http") {
return { host, port, protocol };
}
config(undefined, 3000); // { host: "localhost", port: 3000, protocol: "http" }
Best Practice
- Đặt tham số có default ở cuối (convention chung, dễ đọc).
- Nếu cần skip middle param → dùng Object Destructuring (options object pattern):
function config({ host = "localhost", port = 8080, protocol = "http" } = {}) {
return { host, port, protocol };
}
config({ port: 3000 }); // { host: "localhost", port: 3000, protocol: "http" } - rõ ràng, không nhầm vị trí
Default Parameter Evaluation
Default expression được evaluate mỗi lần gọi function (không phải lúc define):
let counter = 0;
function inc(x = ++counter) {
return x;
}
inc(); // 1
inc(); // 2
inc(); // 3