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);
})