Why will you use default parameters in Javascript?

Faisal Ahmed - Dec 23 '21 - - Dev Community

By default, default parameter is undefined in a function.
If you can not set a parameter in a function, the program output shows NaN. So you should set the default parameter.
Example:

function myFunction(x,y=2){
  return x+y;
}
console.log(myFunction(5));
//the output is : 7
//y=2 is a default parameter.
Enter fullscreen mode Exit fullscreen mode

  • If you can't pass parameter, but you set default parameter, then you get the correct output. Example:
function myFunction(x=5){
  return x;
}
console.log(myFunction());
//the output is : 5
//x=5 is a default parameter.
Enter fullscreen mode Exit fullscreen mode

  • If you pass parameter, and also you set default parameter, then you get what you pass inside of a function. Example:
function myFunction(x=2){
  return x;
}
console.log(myFunction(5));
//the output is : 5
//x=2 is a default parameter.
Enter fullscreen mode Exit fullscreen mode

  • If you pass parameter, and also you set default parameter as undefined, then you get the default parameter value. Example:
function myFunction(x=2){
  return x;
}
console.log(myFunction(undefined));
//the output is : 2
//x=2 is a default parameter.
Enter fullscreen mode Exit fullscreen mode

  • If you pass parameter, and also you set default parameter as null, then you get the output null. Example:
function myFunction(x=2){
  return x;
}
console.log(myFunction(null));
//the output is : null
//x=2 is a default parameter.
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .