tags:

views:

89

answers:

7

I have been using javascript for a while now and am starting to realise how badly I have been using the language. Some more advanced aspects of it are comming to light such as closures, module pattern etc.

Can someone explain how the () operator works when placed at the end of a function i.e. why does it immediately invoke it - i havent seen this before and am puzzled as to how this actually works.

as in:

var myFunct = function() {
    alert("here");        
}();

The () at the end will immediately invoke the function.

+2  A: 

A function is an object. Using function_name refers to the actual function object. And function_name() refers to the result of the function. For example:

function foo() {
  return 2;
}

typeof foo()
= "number"

typeof foo
= "function"
remi
Right, and to explain further: placing () at the end of any object tells javascript to execute that object as a function.
Josiah Kiehl
I prefer to think of the expression `function_name` resulting in the function-object which is then applied ("run") by the function invocation/application (`(...)`) operator. The result of the application is thus the result of the expression `function_name()`. In the case of `(function () { ... })(...)` the same thing holds. Just in this case the function-object is the result of the `(function () { ... })` expression and not `function_name`. Since `(...)` is just an operator it can be applied to *any* expression resulting in a function-object.
pst
+2  A: 

The () construct means "function call". The thing about JavaScript that's different from some other languages is that identifiers are not the only thing you can call as a function. So from C, something like this might look familiar:

fnName();

But in JavaScript, any expression can evaluate to a function, which means it can be called as a function call. Like so:

(function () {/*do something*/})();

The parentheses around the function expression are necessary to group expressions so that the second set of parentheses is a function call on the expression in the first set of parentheses.

Zach
+1  A: 

That's simply the syntax for invoking a function:

function foo() { alert('Purple is a nice colour') }
foo();    // Invokes the 'foo' function

Similarly, since in Javascript functions are first-class objects, one can do:

var foo = function() { alert('I like camels') };
foo();    // Invokes the function that the variable 'foo' has a reference to

This can even be expressed without using an intermediate variable (since a function is an object):

(function () { alert('Ponies are cool') })();    // Creates a function object, then invokes it
Cameron
A: 

If () didn't invoke the function, then some other syntax would have to. It's just a choice of syntax for a function call, chosen for its familiarity from many earlier languages. The arguments, if any, go in the parentheses.

It's hard to see how you could have done anything in Javascript without encountering function calls.

Daniel Earwicker
A: 

I assume that you mean an anonumous function that is executed immediately (and according to your edit, my assumption was right):

(function(){...})();

It works for any value that references a function, for example:

var x = function(){};
x();

function y(){}
var z = y;
z();

Or even a function that returns a function reference:

function a() {
  return function(){};
}
a()();
Guffa
A: 

Javascript functions are first-class objects. They can be stored, passed and returned. Since they're functions, they can also be called.

So you can write this:

var f = function(message) {
    window.alert(message);
}

f("Hello, world!");

That creates an anonymous function object and stores it into f. Then it calls it through f.

You can also create an anonymous function object and call it immediately without storing it in a variable:

function(message) {
    window.alert(message);
}("Hello, world!");
Frédéric Hamidi
+1  A: 

In JavaScript, functions are objects too, and by applying the () operator to it, you will invoke the function and the invocation will evaluate to the result returned from the function.

As such, let's break down your statement, which is:

var myFunct = function() {
    alert("here");        
}();

First, you define a function, so let's "refactor" this so that part becomes clearer.

var myFunctionDeclaration = function() {
    alert("here");        
};
var myFunct = myFunctionDeclaration();

Now, it should be easier to see that you're invoking the function in your code.

Function declarations aren't statements that need to be by themselves, but can be used as expressions that return the function object.

So basically your code was this:

var myFunct = (expression that produces function object)();
                                                        ^^
                                                        +--- invoke the function

This means that you can chain this together. If your function returns another function, you can call this new function as well, in the same statement.

For instance:

var myFunct = function() {
    alert("here");
    return function() {
        return 10;
    };
}()();
 ^ ^
 | +-- calls the inner function, that was returned when calling the outer
 |     function
 |
 +---- calls the outer function, which returns a new function object
// myFunct ends up being 10
Lasse V. Karlsen