Default Function Arguments
If you come from another language, you must be aware of this feature called “Default Params” or “Default Function Arguments”.
The idea is very simple, in case there is no value or undefined passed in the functional argument, we already take care of this case in the function definition.
The idea is to initialize parameters with some default values in case no value or undefined is passed.
Example 1
Write a function to displlay greeting message from a person whose details are taken in the arguments (Handle the edge case where one of the arg might be missing by displaying some generic values
Let’s see how can we solve this without default params
// Without default params
function greet (name, age, profession) {
if (!name || !age || !profession)
return `Greetings, I am <anonymous>
I am 20 years old.
I am a student`;
else
return `Greetings, I am ${name}
I am ${age} years old.
I am a ${profession}`;
}
console.log ("With all args: \n", greet ("John", 25, "SDE"));
console.log ("Without all args: \n", greet (16, "Student"));
Solution to the above problem using default params
// Using default params
function greet (name="anonymous", age=20, profession="stutdent") {
return `Greetings, I am ${name}
I am ${age} years old.
I am a ${profession}`;
}
console.log ("With all args: \n", greet ("Kepler", 22, "Student"));
console.log ("Without all args: \n", greet ());
That’s it for today, see you in DailyJS tomorrow :)
Download your free eBook