0

Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}

In Javascript I can write:

function TheFunc(arg) {
   ...
}

or

TheFunc = function(arg) {
   ...
}

or

TheFunc : function(arg) {
   ...
}

What's the real difference and when should I use which?

Community
  • 1
  • 1
alexeypro
  • 3,633
  • 7
  • 36
  • 49
  • The third will give you a syntax error, unless you put a function name on it, (the [label statement](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#label_Statement) doesn't expect an Expression, but another statement). Possible duplicate of http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname – Christian C. Salvadó Apr 27 '10 at 05:04
  • And there is many similar questions on Linked section of that question http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname – YOU Apr 27 '10 at 05:08
  • Third one can be: xxx = { helloFunc : function() { ... } } - that's valid. But when? – alexeypro Apr 27 '10 at 05:09

1 Answers1

0

One difference between the first and second syntax that's not mentioned (not in the linked questions as well) is that if the function returns a function object the results of using 'TheFunc' will be quite different

TheFunc = function(arg) {
  return function(x) {
    return arg+x;
  }
}(5);
res = TheFunc(2); // res == 7

making it equivalent to

TheFunc = function(5) {
  return function(x) {
    return 5+x;
  }
}
res = TheFunc(2); // res == 7

because the function was anonymous. While

function TheFunc(arg) {
  return function(x) {
    return arg+x;
  }
}

byFive = TheFunc(5);
res = byFive(2); // res == 7

would have the same result, but making the function factory reusable.

The practical uses won't be that clear in these examples, however it can be indispensable, for example, in situations where a complex hook system exists built around callback based calls - such as systems with plug-ins:

// state object
function state(args) {
  this.parse = function(data){
    data = this.pre_parser(data);

    // go on transforming data

    return data;
  }
}
state.prototype.pre_parser_factory = function(options){
  ...
}

var st = new state(args);
async_call( function(data, options){
              st.pre_parser = st.pre_parser_factory(options);
              res = st.parse(data);
            })
Nick
  • 109
  • 5
  • Apart from hoisting, which only affects whereabouts in the code a function is defined, there is no practical difference between a function created using a function declaration and one created using a function expression. Is your point just that you can call a function created with a function expression immediately? – Tim Down Apr 27 '10 at 09:13