3

From what I have heard, the following is a "self-calling function":

func(){}();

How is it different from the following?

func(){} func();
0

1 Answer 1

12

I assume you meant what is the difference between (I):

function(){}();

and (II):

function func(){};
func();

or even (III):

var func = function(){};
func();

All three behave the same in regard to the results, however they have different naming and scoping consequences:

  • I: this will not make the function available under any name, it is run once and forgotten. You can not reference it in the future

  • II: func function is created and available in the whole enclosing function, even before it is defined (hoisting)

  • III: func variable is defined pointing to a function. It won't be accessible before being defined.

Note that in II and III the function is referencable via func name and can be called again multiple times. This is not possible with self-calling function in I.

Sign up to request clarification or add additional context in comments.

2 Comments

Agreed, but then under what scenarios are self-calling functions used? I mean is there any specific need for them to be used in some sort of particular scenario?
I know this is old but for other readers: you can wrap all of your own javascript in one big self-calling function so that it runs, but you know that it won't add a variable name to the global namespace - then, no other plugins like jQuery or anything else could accidentally use the same name as yours and clash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.