skip to Main Content

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


  1. How would this make it easier to identify the function in debugger stack trace?

    Because it lists the function in the stack trace as fac instead of (on of many) anonymous functions.

    Screenshot showing 'fac' in the stack trace


    What’s the point of combining these 2?

    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.

     myArray.sort(function caseInsensitiveAlphaSort() { ... });
    

    or using the function in a context where the factorial variable might be overwritten due to asynchronous shenanigans.

    Login or Signup to reply.
    1. Anonymous functions like arrow functions obfuscates the stack trace. So if you provide the name, it really is easier to debug because you see the name in stack trace.
    2. And, using the name, the use of recursion will be easier – like you see there in MDN docs in that particular example you posted already!

    Afaik those are the points for use that way to create a function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search