Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Self-Executing Anonymous Functions in javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 204
    Comment on it

    As we all know in javascript we mostly use function ,if statement,loop and event handlers.These terms help us organize your code into a cohesive, structurally-sound whole.

    Let's take one example of javascript function:

     

    var foo = 'Hello';
    var bar = 'World!';
    
    function baz(){
      return foo  + ' ' + bar;
    }
    
    console.log(baz());

     

    If we will see that function will work fine and does not create any issue at least for now.
    but when we are creating a big application then this code will start to become an unwieldy mess. So to overcome that problem we will make our function Self-Executing Anonymous Functions. Below is the example of Self-Executing Anonymous Functions is:

     

    (function(){
      console.log('Hello World!');
    })();

     

    If we will see the above code then we know that above code is made up of two key parts

    First key part is below:

    (function(){
      //Normal code goes here
    })

    second key part is as follow:

    ();

     

    These two bracket shows that every code in these bracket to be executed immediately and we know all the function and variable that are defined in anonymous function cant be access outside of function. Lets take the example to explain above paragraph.

     

    var foo = 'Hello';
      var bar = 'World!'
      
      function baz(){
          return foo + ' ' + bar;
      }
    })();
    
     //These all throw exceptions:
    console.log(foo);
    console.log(bar);
    console.log(baz());

     

    this line will throw exceptions because we are trying to access inaccessible  variable and function. To use these function we will use global 'window' object.

    (function(){
      var foo = 'Hello';
      var bar = 'World!'
      
      function baz(){
          return foo + ' ' + bar;
      }
    
      window.baz = baz; //Assign 'baz' to the global variable 'baz'...
    })();
    
    console.log(baz()); //...and now this works.
    
    //It's important to note that these still won't work: 
    console.log(foo);
    console.log(bar);

     

    So this is the detail explanation of Self-Executing Anonymous Functions in javascript.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: