Function with no argument can use default parameter as its default value.
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")} `); // Calling greet with param Raj = Welcome Mr.Raj
console.log(`Calling greet without param = ${greet()} `); // Calling greet without param = Welcome Mr.noob master
console.log(`Calling greet with empty string as param ${greet("")} `); // Calling greet with empty string as param Welcome Mr.
Before Es6 we need to check for the existence of a variable and give a value.
function greet(name) {
if(typeof name == undefined) {
name = "Joe";
}
console.log("Welcome Mr." + name); // Welcome Mr. Joe
}
Another example on how to use default parameter.
function test(num = 1) {
return num;
}
test(); // 1
test(undefined); // 1
test(null); // null
test(false); // false
test(NaN); // NaN
Notice that in the above code the default parameter value only applies when the parameter value is undefined.
We can also use another function parameter when declaring a default value. here num1 is accessed and can be treated like any other variable.
function test(num1 , num2 = num1 * 2) {
console.log(num1 * num2);
}
test(2); // 8
test(2,3); // 6
functions can also be used as default values.
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.Anitha
greet("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)); // 100
console.log(square()); //25
That will be all.