Learn about how and when to use default parameters in Javascript.

Default parameter in Javascript
The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined).
In a function, Ii a parameter is not provided, then its value becomes undefined. In this case, the default value that we specify is applied by the compiler.
Example:
function greet(name = "noob master") {
console.log("Welcome mr." + name);
}
greet("Jagathish"); // Welcome mr.Jagathish
greet(); Welcome mr.noob master
greet(""); Welcome mr.
If we donβt use a default parameter (not available pre-ES6), then we would need to check for the existence of the variable and set it ourselves.
function greet(name) {
if(typeof name == undefined) {
name = "noob master";
}
// second way is
name = name || "noob master";
console.log("Welcome mr." + name);
}
Below is another example of using a default parameter. Notice that it only applies when the value is undefined.
function test(num = 1) {
console.log(num);
}
test(); 1
test(undefined); 1
test(null); null
test(""); ""
test(false); false
test(NaN); 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); 8
test(2,3); 6
In the above code, num1 is accessed in default value assignment to 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("Jagathish") //default Good morning mr.Jagathish
greet("Jagathish", customGreet); //Custom Good morning mr.Jagathish
We can set a default value by evaluating a function and using the value returned.
function getDefaultNum() {
return 5;
}
function square(num = getDefaultNum() ) {
return num * num;
}
square(10); // 100
square(); //25
We can have default parameters in any order, and this 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); // 10,10,100,undefined
test(100); // 100, undefined, 100 , undefined
test(); // 10, undefined, 100, undefined
Do follow me Javascript Jeepππ¨Β .
Please make a donation here. 80% of your donation is donated to someone needs food π₯. Thanks in advance.