In the ES5 days, to set default values you might write your code in this manner:
function getSum(a, b){
a = (a !== undefined) ? a:1;
b = (b !== undefined) ? b:41;
return a + b;
}
getSum() //42
getSum(1,2) //3
or
function getSum(a, b){
a = a || 1;
b = b || 41;
return a + b;
}
getSum() //42
getSum(1,2) //3
These are good solutions, but hey it's 2019, Modern JavaScript is here to rescue us from this long walk. Now, you can set default values to the parameters in the function declaration statement itself like so:
function getSum(a = 1, b = 41){
return a + b;
}
getSum() //42
getSum(1,2) //3
If you don't specify an argument, the default value of the parameters gets used.
Compared to the older methods of setting default values, this new feature provided by ES6 is easier and much cleaner.
Happy Coding!❤
Top comments (14)
What if I specify an argument with an
undefined
value?Good question!!, the same thing applies. The only difference in this case is that you are explicitly setting your argument to be undefined. The trick here is, whether you specify undefined explicitly or allow JavaScript to do it for you implicitly, the important thing to note is that once JavaScript reads undefined it uses the default parameters
undefined
logically means that you are not specifying the argument. So it will use default value.Default values are one of the best additions to JavaScript.
I'd like to mention in this example, using the
||
short circuit evaluation will result in bugs.In this example,
getSum(0, 0)
will return42
.The reason is
0
isfalsy
and therefore will result in1
fora
and41
forb
.Cheers!
Yes in fact, Thank you for spreading more light on that path. That's why the default function parameters is indeed a boon to JavaScript. We're saved from these quirks that could leave us banging our heads on our monitors all day long!... Thanks for reading and happy coding!!
And don't forget that the second option doesn't play nice with "falsy" numbers, like 0. :D
i dont know why this usefull feature is not available from early ecma script versions.this is ordinary feature in other languages
You are right. You know JavaScript was created in a haste, it was created to simply add interactivity to web pages. But as time goes, with the invention of sophisticated frameworks and its application in the server (nodejs). JavaScript had to level up
Default params in JS are a boon.
You can say that again!, thanks for reading
What are Default Functions? As far as I know this is called default parameters.
Thanks for pointing that out, it has been corrected . Much love !
How to set only the second parameter?
or