Set Default Parameters for Your Functions - how to understand code

Tell us what’s happening:

I solved the challenge but I don’t understand why the function is written this way and how to read it. In particular, I’m very troubled by the use of the ‘increment’ function twice.
My best guess is:

  • we declare a const increment that is a function
  • this const function returns an increment function (different from the first increment function as it’s within the first function)
  • the inner function takes 2 arguments, number and value and returns the sum of both

Is this interpretation correct?

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 6

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

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

I’ll skip the code you mentioned because it’s not the point of this “challenge”.

The main thing here is understanding the default function parameters and I recommend looking at the code in the challenge description, which is this:

function greeting(name = "Anonymous") {
  return "Hello " + name;
}
console.log(greeting("John")); // Hello John
console.log(greeting()); // Hello Anonymous

Basically, name = "Anonymous" makes the name parameter equal “Anonymous” if nothing else has been passed in. For now, that’s really all you really need to know about default parameters, you can use them in all the functions you’ve been writing up to this point.
The rest of the code (a nested function, use strict, IIFE, etc.) doesn’t serve a purpose beyond distracting you. I assume they just needed to write it this way so the challenge would work.