Thursday 19 June 2014

The self-executing anonymous function

There are three parts to it:
1. It's anonymous and does not have a name.
2. It self executes.
3. It's a function.

Well, a self-executing anonymous function has it's own uses.

First case, where you need to execute some functionality without it effecting other surrounding functionality nor the surrounding environment effecting it. It basically creates a local private execution area bereft of the outside environment.

Example:

var name  = 'The Master Dev';

(function () {
    var name = 'The Rookie Dev';
    console.log(name); // Outputs "The Rookie Dev"
}) ();

console.log(name); // Outputs "The Master Dev"

Second case, where lets say you have a lot of code inside a <script> block and you want to test breakpoints and exit and not execute the remaining code, then in this case surrounding the entire code in a anonymous function and using return as an exit point helps.

Example:

<script>

var line = 'Hello World';

// some code
// here

// Need to debug here and exit

// and here

</script>

With self-executing anonymous function:

<script>

(function () {
    var line = 'Hello World';

    // some code
    // here

    return;

    // and here
});

</script>

No comments:

Post a Comment