3

So I am confused as to when I would use an anonymous function such as:

let foo = function () {
  //code
}

versus a named anonymous function such as:

let foo = function foo () {
  //code
}

Besides browser support, namely IE, are there any differences between the two? When should I use one over the other?

6
  • 1
    Neither of them are anonymous. In both cases foo.name is foo Commented Jan 30, 2018 at 6:50
  • 1
    use a name to self-refer to it within the function, since you can't use arguments.callee in use strict Commented Jan 30, 2018 at 6:50
  • The second function is not anonymous since you just gave it a name. Commented Jan 30, 2018 at 6:50
  • @gurvinder372 the first function is anonymous and assigned to a variable. The second is also assigned, but it's named. Commented Jan 30, 2018 at 6:50
  • @HubertGrzeskowiak Then how come they have same name property value? Commented Jan 30, 2018 at 6:51

1 Answer 1

4

In this case, where the function declaration name is the same as the variable it is assigned to, it doesn't make much difference.

If you used a different name for the definition and assignment, the name on the right takes precedence in naming the function:

foo = function bar() {}
foo.name  // "bar"

In both cases you assign your function to a variable (function expression), but in the first case you assign an unnamed/anonymous function, whereas in the second case you assign a named function. When assigning an anonymous function to a variable in such a simple expression, the JS engine is able to name the function properly.

Consider the following case where this assignment is non-obvious for the engine:

function p(fun) { return fun; }
foo = p(function() {})
foo.name  // empty string

TL;DR; with named functions you often get better stack traces.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.