Function returning a function of same name

Function returning a function of same name
0

#1

Tell us what’s happening:
I dont understand the way functions are used in this snippet. An anonymous function is assigned to sum. But, why does it return a function with the same name? can’t it just be
const sum = function(x, y, z) {
rest of the function
}

Your code so far


const sum = (function() {
  "use strict";
  return function sum(x, y, z) {
    const args = [ x, y, z ];
    return args.reduce((a, b) => a + b, 0);
  };
})();
console.log(sum(1, 2, 3)); // 6

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-the-rest-operator-with-function-parameters


#2

sum actually contains the named inner sum function that gets returned when the IIFE runs.

So it’s more like this:

const sum = function sum() {...function body}

Not this:

const sum = function() {...function body}

The first function will show up in the call stack as sum, the latter will show up as anonymous.

As to your question of why I don’t really think there is a very good reason for it. As far as i can tell, the only effect of using the IIFE is that the “use strict” directive is scoped to it, as opposed to being scoped to the outer variable environment.

Meaning you can do this:

// Sum gets implicitly assigned to the global scope, because it was not declared, and the "use strict" directive is not in scope.
sum = (function() {
  "use strict";
  return function sum(x, y, z) {
    const args = [ x, y, z ];
    return args.reduce((a, b) => a + b, 0);
  };
})();

But you can not do this:

// Sum gets implicitly assigned to the global scope
sum = (function() {
  "use strict";
  return function sum(x, y, z) {
    // Reference Error, because of the "use strict" directive, args will not be implicitly assigned to the global scope
    args = [ x, y, z ];
    return args.reduce((a, b) => a + b, 0);
  };
})();