This code appears in a very popular JS tutorial:
const sum = (function() {
"use strict";
return function sum(...args) {
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3)); // 6
I am trying to make sense of the reason they return a function from a function (explanation is not provided there, unfortunately). It would be simpler and straightforward if the outer function is declared with parameters, perform the calculation, and then simply return the value. Why would there be a necessity (in this case; seems like an answer to the general case can be found here) to express a function this way?
Is there any reason to express a function instead of declaring it? i.e, to express a function as a
var
,let
orconst
instead of simply declaring it with thefunction
keyword? What are the advantages of each way? I read here that besides hoisting, it is entirely a stylistic decision. Wouldn't it then, be safer to always declare functions rather than expressing them? I must be missing something basic here.