wOlVeRiNe
wOlVeRiNe

Reputation: 575

What are self-calling functions in JavaScript?

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

func(){}();

How is it different from the following?

func(){} func();

Upvotes: 3

Views: 2601

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

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.

Upvotes: 12

Related Questions