The purpose of "return function"?

The purpose of "return function"?
0.0 0

#1

It looks like increment is set to an anonymous function that returns another increment function? What is the purpose? Why not just declare the increment function?

What does the “return function” syntax mean?

Your code so far


const increment = (function() {
  "use strict";
  return function increment(number, value) {
    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 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

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


#2

There’s actually two concepts here, a self-invoking function, and a closure.

A function wrapped like (func(){})(); is a self invoking function. That means the function will run immediately as soon as it’s declared. So when the javascript engine gets to this line

const increment = (function...

the engine will assign the increment variable to the result of the function, and not the function itself. And the result of this function is another function, which is a closure.

Closures are a complex concept that trips up even experienced devs.


#3

Thanks. If I understand correctly, this is also a curried function?


#4

Yes, the returned function is the curried function. It’s easier to see this using arrow function. I’ve removed the iife for clarity.

/*
increment is a function that 
- takes 0 arguments,
- and returns a function that 
  - takes 2 arguments, 
    - that then returns a sum
*/
const increment = function() {

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

// is the same as
const increment = () => (number, value) => number + value