Hello, strangers.
I’m new to programming so I’m quite confused and clueless most of the time. Can someone explain why there’s an opening parenthesis before the function keyword? Also, why create a function called sum and then return that exact function? I’ve never seen anything like this before. Thanks in advance.
const sum = (function(...args) {
"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
Hello
Good question : why create a function called sum and then return that exact function? const sum define a constant reference to function sum(...args){...}.
if we try this :
function sum(...args) {
return -1;
}
we get this error :
SyntaxError: redeclaration of const sum
this protect sum from being accidentally changed when code grow.