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

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:

Your code so far


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

Your browser information:

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.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions

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;
 }
 
 console.log(add(2, 8)); // Print 10
1 Like

@Gilbert1391

I think that we understand that and is just replace value for value = 1, but in overall, what is doing the code? Why not just:

const increment(num, value = 1){
    return num + value
}

In the code it’s like you are activating the function after is defining it

const increment = ()()

and the variable gets the function defined inside (The outer function returning an inside function).

const increment =  function increment(number, value = 1) {
    return number + value;
}

And you use the type number , why not just a variable in the inside function.
number is a keyword, and it’s getting override by a value?

the external function is there for the sake of the tests, and to activate strict mode, you can ignore it

It’s like inception xDD

I have edited my post.