# Set Default Parameters for Your Functions-- explaine the code?

Set Default Parameters for Your Functions-- explaine the code?
0

#1

So, I solved the problem. Basically I tried hit and trial method to solve the problem. But I really didn’t get why the code working like this. So, when we passed the value (5, 2) so 5 assign to number, right? and 2 to value? but on this line return function increment(number, value = 1) we already assign value = 1. I don’t get this thing.

Tell us what’s happening:

const increment = (function() {
"use strict";
return function increment(number, value = 1) {
return number + value;
};
})();
console.log(increment(5, 2)); // returns 7
console.log(increment(5)); // returns NaN

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

#2

The lesson is talking about a function default parameters. What does this mean? It means that you can set default values to a function parameters and when you call the function, if you don’t define the parameters value, then the function will execute with the value that you set as default. Example:

const add = (num1, num2 = 4) => { // Here we are setting the val of parameter num2 equal to 4, we are setting a default parameter.
return num1 + num2;
}

console.log(add(2));  // Here we are calling the function with only one parameter
// But because we set a default value to  its second parameter
//  Then the function will take that value, and do whatever it is that you want it to do
// In this case, it's a sum. So 2 + 4(default parameter) = 6

if you want to define both parameters when calling the function, you can do that too:

const add = (num1, num2 = 4) => {
return num1 + num2;
}