The default parameter is used to set a default value for a function parameter for which no argument is passed.
If a parameter is not provided in a function, then its value becomes undefined. In this case, the default value that we specify is applied by the compiler.
function greet(name = "noob master") {return "Welcome Mr." + name;}console.log(`Calling greet with param Raj = ${greet("Raj")} `);console.log(`Calling greet without param = ${greet()} `);console.log(`Calling greet with empty string as param ${greet("")} `);
If we do not use a default parameter (not available pre-ES6), then we need to check for the existence of the variable and set it ourselves.
function greet(name) {
if(typeof name == undefined) {
name = "master";
}
// second way is
name = name || "master";
console.log("Welcome Mr." + name);
}
The following is another example of how to use a default parameter. Notice that the default parameter value only applies when the parameter value is undefined.
function test(num = 1) {return num;}console.log(`Calling test without param = ${test()} `);console.log(`Calling test with undefined = ${test(undefined)} `);console.log(`Calling test with null = ${test(null)} `);console.log(`Calling test with empty string = ${test("")} `);console.log(`Calling test with false = ${test(false)} `);console.log(`Calling test with NaN = ${test(NaN)} `);
We can also use another function parameter when declaring a default value.
function test(num1 , num2 = num1 * 2) {console.log(num1 * num2);}test(2);test(2,3);
In the above code, num1
is accessed in the default value assignment of num2
.
We can also use a function as a default value. Functions are first-class citizens in JavaScript and can be treated like any other variable.
function greet(name, greetMethod = defaultGreet) {greetMethod(name);}function defaultGreet(name) {console.log("Default Good morning Mr." + name );}function customGreet(name) {console.log("Custom Good morning Mr." + name);}greet("Anitha") //default Good morning mr.Anithagreet("Anitha", customGreet); //Custom Good morning mr.Anitha
We can set a default value by evaluating a function and using the returned value.
function getDefaultNum() {return 5;}function square(num = getDefaultNum() ) {return num * num;}console.log(square(10)); // 100console.log(square()); //25
We can have default parameters in any order, which means we can have non-default parameters after default parameters.
function test(a = 10, b, c =100 , d) {console.table({a, b, c, d});}test(undefined, 10);test(100);test();