With default parameter values added in ES2015, you can declare default values for the parameters, and when making the call, if you pass undefined
as the first parameter, it will get the default:
function test(a = "ay", b = "bee") {
console.log(`a = ${a}, b = ${b}`);
}
test(); // "a = ay, b = bee"
test(1); // "a = 1, b = bee"
test(undefined, 2); // "a = ay, b = 2"
test(1, 2); // "a = 1, b = 2"
You can do something similar yourself manually in a pre-ES2015 environment by testing for undefined
:
function test(a, b) {
if (a === undefined) {
a = "ay";
}
if (b === undefined) {
b = "bee";
}
console.log("a = " + a + ", b = " + b);
}
test(); // "a = ay, b = bee"
test(1); // "a = 1, b = bee"
test(undefined, 2); // "a = ay, b = 2"
test(1, 2); // "a = 1, b = 2"