DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Why will you use default parameters in Javascript?
Faisal Ahmed
Faisal Ahmed

Posted on

Why will you use default parameters in Javascript?

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

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.