0

Possible Duplicate:
What do empty parentheses () after a function declaration do in javascript?

I am looking at some Javascript code and trying to figure out what }(); right after return num+10 means. Does that mean the function will get executed immediately? Where can I get more information about this.

function addToTen(num) {
     return function() {
          return num+10;
     }();
}
addToTen(5); // 15

Thanks, Venn.

Community
  • 1
  • 1
Vennsoh
  • 4,853
  • 5
  • 26
  • 41
  • yes, its an advanced javascript concept, the function is executed as soon as you define it. I am not a JS ninja but can tell you that this function can be used to avoid the global namespace pollution. – Kumar Jun 16 '11 at 05:26
  • 1
    Great question! Someone else was curious about this too: http://stackoverflow.com/questions/2422026/what-do-empty-parentheses-after-a-function-declaration-do-in-javascript – Michael Jasper Jun 16 '11 at 05:29

3 Answers3

3

Yes, but only if it's a function expression, which is different from a function declaration. A function declaration is how your first function is defined:

function foo(){
}

If you add () after this, you get a Syntax Error. If the function is defined as a function expression, adding a set of parenthesis immediately executes it. Functions are expressions whenever they are not defined as above, e.g.:

(function(){}());

var x = function(){}();

return function(){}();

Your actual example is just... odd, and pointless. It's almost a classic closure example, something like:

function addTo(x){
    return function(y){
        return x + y;
    }
}

var addToTen = addTo(10);
addToTen(5); // 15;

but your actual example is equivalent to just:

function addToTen(num){
    return num + 10;
}

and all the extra stuff is completely unnecessary.

1

Yes, it's executed immediately, but the usage doesn't make any sense in this example.

Often used for anonymous functions creating a closure.

see Why do you need to invoke an anonymous function on the same line?

One place where I use it a lot:

(function($) {
    // secure way to ensure no conflict between $ (jQuery)
    // and another js-framework can happen

    $...

})(jQuery);
Community
  • 1
  • 1
roberkules
  • 6,557
  • 2
  • 44
  • 52
1

Yes, it means the function object is evaluated.

Just like with any other function, you have two ways of looking at it:

var myFunction = function(val) {
    return val + 1;
}
  1. To return the function object, or send it somewhere else, I just say myFunction
  2. If I wish to execute it, I say myFunction()

In this closure or decorator, whatever, that you've described above, rather than return the function object itself, you're returning the value of executing that function immediately, hence the () afterwards.

Jordan
  • 31,971
  • 6
  • 56
  • 67