-4

few years back people always define function like this way

1) function foo() {}

now i have noticed people define function like this way

2) var foo= function () {}

3) foo: function() {}

4) var GaugeBar = GaugeBar || {};
   GaugeBar.generate = function (percentage) {}

so anyone JavaScript expert would tell me why people follow different approach for defining function? each signature has any special significance ?

when we should follow which one?

looking for good explanation. thanks

Thomas
  • 33,544
  • 126
  • 357
  • 626
  • 1
    Options 3 and 4 aren't just defining functions. – JLRishe Jan 03 '15 at 19:53
  • so tell me what is option 3 and 4. – Thomas Jan 03 '15 at 19:54
  • 3
    They are defining methods on an object (option 3 is not a complete JavaScript statement on its own). If you didn't know that, I suggest going through some tutorials on JavaScript, particularly about how to create and use objects. – JLRishe Jan 03 '15 at 19:56

1 Answers1

0

I think that there is some confusion in your question - the only valid approach to define a function is 1) and 2). The other two are just different uses of functions in objects.

I personally like to define named functions (function myFunc () {}) because if my program crashes the function names will appear in stack traces. However, there are situations where I use anonymous functions if those functions are not part of a public API or if they are used only once in my program.

Option 3) is basically a function that gets assigned to an object:

var myObject =
{ func: function () {}
, func2: function () {}
}

Option 4) is merely a way how to ensure that a variable contains an object and after that adding some functions to that object.

In practical terms, there is no difference whether you give your functions a name or you use anonymous functions (except for the stack traces and for differences already described in this SO question) and I believe it depends on the programmer's preferred code style. I would love if everyone named their publicly accessible functions as it makes debugging easier, but that's up to each developer to decide.

Community
  • 1
  • 1
Robert Rossmann
  • 11,931
  • 4
  • 42
  • 73