+ 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
4 Respostas
+ 2
It is right since 5 is passed to the first parameter a
+ 1
Abhay! thank you for prompt reply. I am taken.
+ 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?
0