According to MDN docs (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions), you can use both a function declaration and function expression, because:
However, a name can be provided with a function expression. Providing
a name allows the function to refer to itself, and also makes it
easier to identify the function in a debugger’s stack traces:
The code:
const factorial = function fac(n) {
return n < 2 ? 1 : n * fac(n - 1);
};
console.log(factorial(3)); // 6
My question is:
- How would this make it easier to identify the function in debugger stack trace?
- A function can also refer to itself if it were to be one or the other.
So basically: What’s the point of combining these 2? I simply cannot wrap my head around it.
2
Answers
Because it lists the function in the stack trace as fac instead of (on of many) anonymous functions.
There’s no benefit for using a local variable in the outer scope and a name for referencing the function in this example.
It appears to be a simplified example to demonstrate how it works and not why it is useful.
Consider if you are passing the function as an argument instead of assigning it to a variable.
or using the function in a context where the
factorial
variable might be overwritten due to asynchronous shenanigans.Afaik those are the points for use that way to create a function.