+ 1

Default parameters in ES6

The result of the function mentioned below is a little bit odd ! Someone can explain it, please. function test(a, b = 3, c = 42) { return a + b + c; } console.log(test(5)); //50

4th May 2020, 10:44 AM
Unar Arbab
Unar Arbab - avatar
4 Respuestas
+ 2
It is right since 5 is passed to the first parameter a
4th May 2020, 10:47 AM
Abhay
Abhay - avatar
+ 1
Abhay! thank you for prompt reply. I am taken.
4th May 2020, 10:54 AM
Unar Arbab
Unar Arbab - avatar
+ 1
You can define the initial value of arguments while writing the function! You should have a clear explanation of this :)) Initial values work when no argument is passed in the function when you call them! Consider this : function test(a = 5, b = 3, c = 42) { return a + b + c; } console.log(test()); // 50 See, you didn’t pass any argument but still getting the output 50 because you defined the initial value of a, b & c. However, again consider this : function test(a = 5, b = 3, c = 42) { return a + b + c; } console.log(test(1, 2, 3)); // 6 This time you get 6 because you passed all three arguments of the function. And hence, the initial values don't work anymore :)) Now here is a quize for you. Tell me the answer without running the code :)) function test(a = 5, b, c = 5) { return a + b + c; } console.log(test(5, 5, 5)); What will be the output?
4th May 2020, 12:09 PM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
0
15th Jun 2022, 9:26 AM
Collins Osuma