What is the purpose of a self executing function in javascript?

What is the purpose of a self executing function in javascript?

In javascript, when would you want to use this:
(function(){
//Bunch of code…
})();

over this:
//Bunch of code…

Solutions/Answers:

Solution 1:

Its all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of javascript code.

For example:

(function(){ 
    var foo = 3; 
    alert(foo); 
})(); 

alert(foo); 

This will first alert “3” and then throw an error on the next alert because foo is not defined.

Solution 2:

Simplistic. So very normal looking, its almost comforting:

var userName = "Sean";

console.log(name());

function name() {
  return userName;
}

However. What if I include a really handy javascript library to my page that translates advanced characters into their base level representations?

Wait… what?

I mean. If someone types in a character with some kind of accent on it (such as a french or spanish character) but I only want ‘english’ characters? A-z in my program? Well… The spanish ‘n~’ and french ‘e/’ characters (I’ve used two characters each for those, but you can probably make the mental leap into the character that represents the accents), those characters can be translated into base characters of ‘n’ and ‘e’.

So someone nice person has written a comprehensive character converter out there that I can include in my site… I include it.

One problem: it has a function in it called ‘name’ same as my function.

This is what’s called collision. We’ve got two functions declared in the same scope with the same name. We want to avoid this.

So we need to scope our code somehow.

The only way to scope code in javascript is to wrap it in a function:

function main() {
  // We are now in our own sound-proofed room and the 
  // character-converter libarary's name() function can exist at the 
  // same time as ours. 

  var userName = "Sean";

  console.log(name());

  function name() {
    return userName;
  }
}

That might solve our problem. Everything is now enclosed and can only be accessed from within our opening and closing braces.

We have a function in a function… which is weird to look at, but totally legal.

Only one problem. Our code doesn’t work.
Our userName variable is never echoed into the console!

We can solve this issue by adding a call to our function after our existing code block…

function main() {
  // We are now in our own sound-proofed room and the 
  // character-converter libarary's name() function can exist at the 
  // same time as ours. 

  var userName = "Sean";

  console.log(name());

  function name() {
    return userName;
  }
}

main();

Or before!

main();

function main() {
  // We are now in our own sound-proofed room and the 
  // character-converter libarary's name() function can exist at the 
  // same time as ours. 

  var userName = "Sean";

  console.log(name());

  function name() {
    return userName;
  }
}

A secondary concern: What are the chances that the name ‘main’ hasn’t been used yet? …so very, very slim.

We need MORE scoping. And some way to automatically execute our main() function.

Now we come to auto-execution functions (or self-executing, self-running, whatever).

((){})();

The syntax is awkward as sin. However, it works.

When you wrap a function definition in parentheses, and include a parameter list (another set or parentheses!) it acts as a function call.

So lets look at our code again, with some self-executing syntax:

(function main() {
  var userName = "Sean";

    console.log(name());

    function name() {
      return userName;
    }
  }
)();

So, in most tutorials you read, you will now be bombard with the term ‘anonymous self-executing’ or something similar.

After many years of professional development, I strongly urge you to name every function you write for debugging purposes.

When something goes wrong (and it will), you will be checking the backtrace in your browser. It is always easier to narrow your code issues when the entries in the stack trace have names!

Hugely long-winded and I hope it helps!

Solution 3:

Self-invocation (also known as
auto-invocation) is when a function
executes immediately upon its
definition. This is a core pattern and
serves as the foundation for many
other patterns of JavaScript
development.

I am a great fan 🙂 of it because:

  • It keeps code to a minimum
  • It enforces separation of behavior from presentation
  • It provides a closure which prevents naming conflicts

Enormously – (Why you should say its good?)

  • It’s about defining and executing a function all at once.
  • You could have that self-executing function return a value and pass the function as a param to another function.
  • It’s good for encapsulation.
  • It’s also good for block scoping.
  • Yeah, you can enclose all your .js files in a self-executing function and can prevent global namespace pollution. 😉

More here.

Solution 4:

Namespacing. JavaScript’s scopes are function-level.

Solution 5:

I can’t believe none of the answers mention implied globals.

The (function(){})() construct does not protect against implied globals, which to me is the bigger concern, see http://yuiblog.com/blog/2006/06/01/global-domination/

Basically the function block makes sure all the dependent “global vars” you defined are confined to your program, it does not protect you against defining implicit globals. JSHint or the like can provide recommendations on how to defend against this behavior.

The more concise var App = {} syntax provides a similar level of protection, and may be wrapped in the function block when on ‘public’ pages. (see Ember.js or SproutCore for real world examples of libraries that use this construct)

As far as private properties go, they are kind of overrated unless you are creating a public framework or library, but if you need to implement them, Douglas Crockford has some good ideas.

Solution 6:

Is there a parameter and the “Bunch of code” returns a function?

var a = function(x) { return function() { document.write(x); } }(something);

Closure. The value of something gets used by the function assigned to a. something could have some varying value (for loop) and every time a has a new function.