Using 2 sets of brackets to call a function

Hi all,

When the return value of a function is another function like:

var outsid_func = function(){
	var infunc = function () { 
		alert("13"); 
	}
	return infunc;
}

the normal method I’ve seen to invoke the returned function is:

var fun_assign = outsid_func();
fun_assign();

In, JavaScript closure for dummies, in the 6th example the returned function is invoked using double brackets like:

outsid_func()();

This is working perfectly in firefox. This is the 1st time I’m seeing a function call like this.

Can you tell me more about this method?
Does this work in all browsers?
Is there any issues with this method?

An alternative

var outsid_func = (function(){
	var infunc = function () { 
		alert("13"); 
	}
	return infunc;

}());

outsid_func();

A self executing function.

As for your version
outsid_func()();

outsid_func() returns a function. you then immediately execute what is returned ( a function ) with the second set of brackets.

Another example

function myFunc(){

  return 'ABCDEFG';

}

console.log( myFunc().toLowerCase() ) // abcedfg

this time the function returns a string so we can immediately run toLowerCase on it. Does that make sense? It’s about what’s being returned.

thanks a lot RLM2008. very good explanation.

why isn’t this method adopted widely?

i searched net for articles about this way of invoking a returned function, but i didn’t find any.

Can any1 help by providing a link to an article etc. that describes this.

Perhaps sometimes you want to run it immediately and sometimes you want to attach it to an event - so you’d only have () when attaching to an event and ()() when running immediately.

I could be missing the obvious, but I can’t think of an example of why you would want to do that.

If you want to execute the inner function immediately then why not do it inside the outer function.

Usually when a function is being returned it’s because you want to do something with it at a later stage. Maybe it’s being attached to an event like onclick or being used in a timer etc.

As I say I could be missing something, but that’s my take.

RLM

Perhaps sometimes you want to run it immediately and sometimes you want to attach it to an event - so you’d only have () when attaching to an event and ()() when running immediately.

I’m sure you’re right, just haven’t bumped into that scenario yet. Or not that I remember.

Atleast you know it’s there if you do need it.