Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: Syntax question

  1. #1
    Regular Coder ninnypants's Avatar
    Join Date
    Apr 2008
    Location
    Utah
    Posts
    504
    Thanks
    10
    Thanked 47 Times in 47 Posts

    Syntax question

    What exactly does setting you code up like this do?
    Code:
    (function(){
         //more code here
    })();
    I've seen it used a lot lately and would like to know what the benefits of it are.
    Last edited by ninnypants; 03-11-2009 at 07:51 PM.

  • #2
    Regular Coder
    Join Date
    Mar 2006
    Posts
    725
    Thanks
    35
    Thanked 132 Times in 123 Posts
    It's a one time call to a function that no longer exists after it returns its value.

    It lets you return an object or a value, calculated or constructed within the function,
    without adding the function itself or any of its internal variables to the environment.

  • #3
    Regular Coder
    Join Date
    Dec 2008
    Location
    Tannhäuser Gate
    Posts
    286
    Thanks
    7
    Thanked 58 Times in 57 Posts
    The code inside this anonymous function will not pollute global namespace.
    When you have some code you need to run once and are concerned about possible conflict between your defined names and other that may be in the global namespace, you can put your code inside such anonymous function.

    It does more or less the same as:
    Code:
    function myfunction(){
         //code here
    }
    myfunction();
    Only in this example you add 1 property to global namespace [myfunction] and the code from your post adds none at all.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •