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.
- function myFunction(arg1, arg2, arg3){
-
- arg1 = arg1 || "agr1";
- arg2 = arg2 || "arg2";
- arg3 = arg3 || "arg3";
-
- console.log(arg1, arg2, arg3);
- }
- function myFunction2(arg1, arg2, arg3){
-
- arg1 = arg1 === undefined ? 1: arg1;
- arg2 = arg2 === undefined ? 2: arg2;
- arg3 = arg3 === undefined ? 3: arg3;
-
- console.log(arg1, arg2, arg3);
- }
Today, ES6 provides a new syntax that can be used to do this in an easier way. Let us see an example below.
- function myFunction(arg1 = 1, arg2 = 2, arg3=3){
-
- console.log(arg1, arg2, arg3);
- }
-
- myFunction(100, 20);
-
- function myFunction2(arg1= 1 , arg2 = 2, arg3=3){
-
- console.log(arg1, arg2, arg3);
- }
-
- myFunction2(1, 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.
- function myFunction(arg1 = 1, arg2 = 2, arg3=3){
-
- console.log(arg1, arg2, arg3);
- }
-
- myFunction(undefined,100, 20);
-
- myFunction(undefined,undefined, 20);
Example of using expressions as your defaults.
- function myFunction(arg1 = 1, arg2 = 2, arg3= (3 * 100)){
-
- console.log(arg1, arg2, arg3);
- }
-
- myFunction(1,22);
- myFunction(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.