JavaScript ES6 - Default Parameter Values

Default parameter values

 
Before ES6, there was no clear way to assign default values to the function parameters that aren't passed. So, programmers usually check the parameters if false or check each parameter if it has an undefined value and assign the default values to them.  
 
Please check out some examples below.   
  1. function myFunction(arg1, arg2, arg3){  
  2.   
  3.     arg1 = arg1 || "agr1";  
  4.     arg2 = arg2 || "arg2";  
  5.     arg3 = arg3 || "arg3";  
  6.   
  7.     console.log(arg1, arg2, arg3); //output arg1 arg2 arg3  
  8. }  
  1. function myFunction2(arg1, arg2, arg3){  
  2.   
  3.     arg1 = arg1 === undefined ? 1: arg1;  
  4.     arg2 = arg2 === undefined ? 2: arg2;  
  5.     arg3 = arg3 === undefined ? 3: arg3;  
  6.   
  7.     console.log(arg1, arg2, arg3); //output 1 2 3  
  8. }  
Today, ES6 provides a new syntax that can be used to do this in an easier way. Let us see an example below. 
  1. function myFunction(arg1 = 1, arg2 = 2, arg3=3){  
  2.   
  3.     console.log(arg1, arg2, arg3);  
  4. }  
  5.   
  6. myFunction(100, 20); //outputs 100 20 3  
  7.   
  8. function myFunction2(arg1= 1 , arg2 = 2, arg3=3){  
  9.   
  10.     console.log(arg1, arg2, arg3);  
  11. }  
  12.   
  13. myFunction2(1, 3); //outputs 1 3 3  
Wow, isn't that nice and elegant? As you can see the syntax is straightforward, isn't? 
 
Just to add a bit more, you can also pass undefined to your function. Lastly, you can also use expressions as your defaults. 
 
Example of passing undefined. 
  1. function myFunction(arg1 = 1, arg2 = 2, arg3=3){  
  2.   
  3.     console.log(arg1, arg2, arg3);  
  4. }  
  5.   
  6. myFunction(undefined,100, 20); //outputs 1 100 20  
  7.   
  8. myFunction(undefined,undefined, 20); //outputs 1 2 20  
Example of using expressions as your defaults. 
  1. function myFunction(arg1 = 1, arg2 = 2, arg3= (3 * 100)){  
  2.   
  3.     console.log(arg1, arg2, arg3);  
  4. }  
  5.   
  6. myFunction(1,22); //output 1 22 300  
  7. myFunction(10, 20, 30); //output 10 20 30  
That's all for now, I'm hoping to create more blog posts about JavaScript in the future. Cheers!
 

Summary 

 
In this blog post, we have discussed the usage of default parameter values. I hope you have enjoyed this blog post, as I have enjoyed writing and coding the examples. Until next time, happy programming.