0

I noticed people in my company like to name functions when assigning it to variables. What are the benefits when it works exactly the same without naming them?

function TargetingForm() {
  'use strict';

  this.setPristine = function setPristine() {
    ...
  }

  //vs

  this.setPristine = function() {
    ...
  }
}
bigpotato
  • 24,574
  • 50
  • 160
  • 313

2 Answers2

4

In order to ensure the name of the function appears in stack traces when debugging (as opposed to showing up as "anonymous function").

However, many modern javascript engines can derive a useful name for stack traces even when the function is declared anonymously in an assignment expression such as in your second example.

es128
  • 1,037
  • 9
  • 11
3

One thing that I can think of (if I am right!) is that you might need to call the function from itself (recursion).

For example you can do this:

function TargetingForm() {
  'use strict';

  this.setPristine = function setPristine() {
    // You can do this
    if (someConditionIsTrue) {
        setPristine();
    }
  }

  //vs

  this.setPristine = function() {
    // You can't do the same here!
  }
}
Omid Kamangar
  • 5,718
  • 9
  • 38
  • 68
  • 3
    Well, you could simply call `this.setPristine()`. And in fact you *should*, as otherwise you're loosing the `this` context – Bergi Jan 27 '15 at 21:24