(…()) vs. (…)() in javascript closures

This question already has an answer here:

  • Location of parenthesis for auto-executing anonymous JavaScript functions?

    4 answers

  • Writing a jasmine test spec to a javascript closure function
  • “this” inside an anonymous function?
  • the right way to pass variable to a callback function
  • Why do you need to invoke an anonymous function on the same line?
  • Function calling itself not working (infinite loop, Javascript)
  • Why is function() needed sometimes in JavaScript?
  • Is there any memory usage difference between anonymous functions and traditional functions in Javascript?if so, hwo?
  • Javascript: closure of loop?
  • Placing arguments for anonymous functions in JavaScript
  • Explain the encapsulated anonymous function syntax
  • How To Access jQuery Event Without Using Anonymous Callback Parameter
  • Javascript anonymous function not updating global variable
  • 4 Solutions collect form web for “(…()) vs. (…)() in javascript closures”

    There’s no difference. Both are valid ways to get the JavaScript parser to treat your function as an expression instead of a declaration.

    Note that + and ! will also work, and are sometimes used by minifiers to save a character of size:

    +function() {  
        var foo = 'bar';  
    !function() {  
        var foo = 'bar';  


    As @copy points out, for completeness, ~ and - will also work.

    -function() {  
        var foo = 'bar';  
    ~function() {  
        var foo = 'bar';  

    That JSLint violation exists because Douglas Crockford says that the outside-parentheses version looks like “dog balls”.

    You can hear him discuss it in this video:

    I think that looks goofy, ’cause what we’re talking about is the whole invocation, but we got these things hanging outside of it looking sorta like … dog balls.

    He suggests that the parentheses inside help the reader understand that the entire statement is a function expression rather than a declaration.

    No, I don’t believe there’s any difference. I personally prefer the former (and jQuery et. al. seem to agree) but they both work identically in every engine I’ve tested.

    Also, JSLint is a little too strict sometimes. JSHint might be a little better in that regard.

    Another form of the immediately invoked function expression that allows capturing a return value is:

    1 && function fnName(params){ return "some result"; }(someParams)

    Also a useful note, if you’re using an IIFE to create a private scope while passing the return value as the parameter to another function, you don’t need any special wrapping. I find it useful when creating a private scope for accessors, like so:

    Object.defineProperty(someObj, 'myProp', function(privateVal){
      return { get: function( ){ return privateVal },
               set: function(v){ privateVal = v    } }