Arrow functions can never be named, like you do with
return function sum(
They can be assigned to a variable, like
const fnName = (...args) => ...
in which case the identifier fnName
will refer to that arrow function, but the arrow function itself won't (and can't) have a name that becomes an identifier inside the function. In contrast, a full function
can have a name, which is what you're doing in the original code with the
return function sum(...args){
// ^^^
line.
Change
const sum=()=>sum(...args)=>args.reduce((a,b)=>a+b);
to
const sum = (...args) => args.reduce((a, b) => a + b);
const sum = (...args) => args.reduce((a, b) => a + b);
const s = [5, 7, 2];
console.log(sum(1, 2, 4, 9))
With function expressions, the function name usually only really matters when you want to reference the function inside itself, without having a standalone outside variable to refer to, eg:
(function foo() {
console.log('foo');
setTimeout(foo, 1000);
})();
This situation is pretty rare, but the technique used above couldn't be done with an arrow function, because arrow functions can't be named - you'd have to save a reference to the function in an identifier first:
const foo = () => {
console.log('foo');
setTimeout(foo, 1000);
};
foo();
A function name puts the function's name into the Lexical Environment (scope chain) that the inside of the function can see.