391

I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...:

// Create a new anonymous function, to use as a wrapper
(function(){
    // The variable that would, normally, be global
    var msg = "Thanks for visiting!";

    // Binding a new function to a global object
    window.onunload = function(){
        // Which uses the 'hidden' variable
        alert( msg );
    };
// Close off the anonymous function and execute it
})();

Ok I see that we will create new anonymous function and then execute it. So after that this simple code should work (and it does):

(function (msg){alert(msg)})('SO');

My question is what kind of magic happens here? I thought that when I wrote:

(function (msg){alert(msg)})

then a new unnamed function would be created like function ""(msg) ...

but then why doesn't this work?

(function (msg){alert(msg)});
('SO');

Why does it need to be in the same line?

Could you please point me some posts or give me an explanation?

Save
  • 11,450
  • 1
  • 18
  • 23
palig
  • 7,651
  • 6
  • 24
  • 18
  • 2
    In other languages these are called Function Pointers or Delegates, if you want to look into the lower-level structures involved. – Chris Moschini Nov 16 '11 at 15:15
  • 17
    You have a ; in the first line – Oliver Ni Nov 29 '13 at 21:43
  • Now that you know how it works... Don't use it. We should [stop writing anonymous functions](http://stijndewitt.wordpress.com/2013/12/02/stop-writing-anonymous-functions/). With just a few more characters we can give our functions a real name and make debugging Javascript code so much more easy! – Stijn de Witt May 14 '14 at 07:55
  • 1
    The line `(function (msg){alert(msg)})('SO');` works completely on its own. It has nothing to do with the other anonymous function you posted before it. Those are two completely seperate anonymous functions. You have to invoke an anonymous function immediately because it has no name and can't be referenced afterwards. – Octopus Mar 25 '15 at 17:46

19 Answers19

384

Drop the semicolon after the function definition.

(function (msg){alert(msg)})
('SO');

Above should work.

DEMO Page: https://jsfiddle.net/e7ooeq6m/

I have discussed this kind of pattern in this post:

jQuery and $ questions

EDIT:

If you look at ECMA script specification, there are 3 ways you can define a function. (Page 98, Section 13 Function Definition)

1. Using Function constructor

var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30

2. Using Function declaration.

function sum(a, b)
{
    return a + b;
}

alert(sum(10, 10)); //Alerts 20;

3. Function Expression

var sum = function(a, b) { return a + b; }

alert(sum(5, 5)); // alerts 10

So you may ask, what's the difference between declaration and expression?

From ECMA Script specification:

FunctionDeclaration : function Identifier ( FormalParameterListopt ){ FunctionBody }

FunctionExpression : function Identifieropt ( FormalParameterListopt ){ FunctionBody }

If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.

This means following is valid.

var sum = function mySum(a, b) { return a + b; }

Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:

var test1 = function test2() { alert(typeof test2); }

alert(typeof(test2)); //alerts 'undefined', surprise! 

test1(); //alerts 'function' because test2 is a function.

Live Demo

Compare this to

 function test1() { alert(typeof test1) };

 alert(typeof test1); //alerts 'function'

 test1(); //alerts 'function'

Armed with this knowledge, let's try to analyze your code.

When you have code like,

    function(msg) { alert(msg); }

You created a function expression. And you can execute this function expression by wrapping it inside parenthesis.

    (function(msg) { alert(msg); })('SO'); //alerts SO.
RubbelDieKatz
  • 1,134
  • 1
  • 15
  • 32
SolutionYogi
  • 31,807
  • 12
  • 70
  • 78
  • 1
    Yeah, but why? Why it need to be as an inline? No matter how many white space I will use. – palig Jul 16 '09 at 20:30
  • 9
    As I wrote, the semi-colon terminated the anonymous function definition. Because it has no name (it's anonymous duh!), you won't be able to call it anymore. If you don't put semicolon then function could still be executed. – SolutionYogi Jul 16 '09 at 20:32
  • I thought that automatic semicolon insertion would put a semicolon in in this case, but it doesn't. So you're right. – Nosredna Jul 16 '09 at 20:49
  • 1
    Nosredna, JS behaves little arbitarily when it comes to adding semi colons. Read this detailed article: http://blog.boyet.com/blog/javascriptlessons/javascript-for-c-programmers-magic-semicolons/ – SolutionYogi Jul 16 '09 at 20:49
  • Yes I see that (function (msg){alert(msg)})('SO'); works. I was just asking why does it work. Where this is specified or what kind of JS feature this is. So once I just call: (function (msg){alert(msg)}) what will happen with the function? It will be GC'ed? – palig Jul 16 '09 at 20:52
  • I would like to think that it will be GCed as and when browser decides. But you do lose the ability to use the function. – SolutionYogi Jul 16 '09 at 21:01
  • palig, I updated my answer with more details about JS function. Hope that helps. – SolutionYogi Jul 16 '09 at 21:24
  • `alert(typeof test1); //alerts 'test1'` No it doesn't. `typeof test1 == "function"` – Justin Johnson Jul 17 '09 at 02:35
  • That's a typo, will correct it. I hope you got the main message though. :) – SolutionYogi Jul 17 '09 at 03:06
  • Ok great update! Here is now all I need to know on the one place.Many thanks! – palig Jul 17 '09 at 04:41
  • I may be mistaken, but I'm pretty sure IE treats named function expressions as function declarations as well, so you can call the function by name outside of the function itself. So in your example, `mySum` would be defined even outside the function block. I'm not positive about that, but either way, IE has some weird bugs with function declarations. :) – Sasha Chedygov Jun 04 '10 at 20:47
  • Douglas Crockford often points out the misinterpretable situations one can inadvertently create by not using semicolons. Personally, I think it's a best practice to use them all the time--it's easier than remembering the times when it's really important and just putting it in then. Per [Crockford's code conventions](http://javascript.crockford.com/code.html): "Put a ; (semicolon) at the end of every simple statement....JavaScript allows any expression to be used as a statement. This can mask some errors, particularly in the presence of [implicit] semicolon insertion." – hotshot309 Jan 06 '12 at 01:38
  • What about `alert(function(a,b) {return a+b;})` ? What kind of function is that and how would you input `a` and `b`? I've seen this a lot in jQuery like, `$('.class').addClass(function() {return 'asdf';});` – chharvey Jul 23 '13 at 20:18
  • There is another way to call anonymous function: (function(msg) { alert(msg); }('SO')); //alerts SO. – Oleksandr_DJ Sep 05 '13 at 08:04
  • @chharvey: Passing a function expression to `alert` does not have so much value. But in the case of jQuery there are many situations where this is useful. Your example with `addClass` does not make much sense to me, but the function `on` accepts a listener, which is a callback function. `on` 'knows' it will be getting a function and it will call this at just the right time. Callback functions are mostly used for asynchronous actions (e.g. an ajax request) or for event handling. – Stijn de Witt May 17 '14 at 20:11
  • @SolutionYogi Thanks so much! I've been wondering this for a while too, being a novice programmer, and it makes sense now! – Jonathan Lam Jul 08 '14 at 20:04
133

It's called a self-invoked function.

What you are doing when you call (function(){}) is returning a function object. When you append () to it, it is invoked and anything in the body is executed. The ; denotes the end of the statement, that's why the 2nd invocation fails.

the12
  • 2,395
  • 5
  • 19
  • 37
seth
  • 36,759
  • 7
  • 60
  • 57
  • Ah ok I see, so it's just some special JS' syntax, right? Like this explanation the most! Simple and short :) – palig Jul 16 '09 at 20:40
  • I think it's incorrect to say that the body will be 'evaled'. It executes just like any other function. Because it is anonymous, either you to save the reference somewhere OR execute it right away. – SolutionYogi Jul 16 '09 at 20:45
  • 16
    Personally, I don't even like the term 'self invoking function'. It's not that function is invoking itself. The programmer wrote those parenthesis to invoke it. – SolutionYogi Jul 16 '09 at 20:48
  • It's not "special syntax" more than anything else is special. Actually, the "function name (args) { BLOCK }" form is much more "special". It is actually unnecessary sugar; this, though, is what actually makes things happen. – jrockway Jul 16 '09 at 21:19
  • jrockway why is that other code block special? Care to elaborate? – SolutionYogi Jul 16 '09 at 21:29
  • The link referenced in the answer is broken. – I. J. Kennedy Jan 04 '13 at 23:13
  • Also you can pass a function into the self-invoking function, this is really neat, not only variable arguments. The ; tells to JS that execute (ends) the anonymous function. – Felix Aug 21 '13 at 21:01
  • 2
    nice link to article . It notes why someone would use this quoted :"In an effort to protect the global object, all JavaScript applications should be written within a self-invoking function. This will create an application scope in which variables can be created without the fear of them colliding with other applications." And also noted "Once the function terminates, the variables are discarded and the global object remains unchanged." – yeahdixon Sep 13 '13 at 18:36
  • This is a great answer that helped me understand anonymous functions after going through a few SO posts – Anupam Dec 19 '17 at 06:35
94

One thing I found confusing is that the "()" are grouping operators.

Here is your basic declared function.

Ex. 1:

var message = 'SO';

function foo(msg) {
    alert(msg);
}

foo(message);

Functions are objects, and can be grouped. So let's throw parens around the function.

Ex. 2:

var message = 'SO';

function foo(msg) {  //declares foo
    alert(msg);
}

(foo)(message);     // calls foo

Now instead of declaring and right-away calling the same function, we can use basic substitution to declare it as we call it.

Ex. 3.

var message = 'SO';

(function foo(msg) {
    alert(msg);
})(message);          // declares & calls foo

Finally, we don't have a need for that extra foo because we're not using the name to call it! Functions can be anonymous.

Ex. 4.

var message = 'SO';

(function (msg) {   // remove unnecessary reference to foo
    alert(msg);
})(message);

To answer your question, refer back to Example 2. Your first line declares some nameless function and groups it, but does not call it. The second line groups a string. Both do nothing. (Vincent's first example.)

(function (msg){alert(msg)});  
('SO');                       // nothing.

(foo); 
(msg); //Still nothing.

But

(foo)
(msg); //works
Benxamin
  • 4,774
  • 3
  • 31
  • 30
  • 6
    Thanks. Your examples were quite clear. I was unaware that parentheses in JavaScript could change the meaning of the code in this way. I come from a Java background, so I learn something new (and often unexpected) about JavaScript almost every day I use it. – hotshot309 Jul 21 '11 at 03:03
  • 5
    Thanks for doing it step by step, this is far better than any other explanation I've seen. +1 – Wk_of_Angmar Dec 25 '12 at 02:12
  • 2
    Major AHA moment here- and thank you for illustrating with substitution. +100 – FredTheWebGuy Sep 07 '13 at 00:47
  • 1
    One of the best explanations I've read about anonymous functions. Thanks a lot! – Teknotica Aug 09 '14 at 11:20
24

An anonymous function is not a function with the name "". It is simply a function without a name.

Like any other value in JavaScript, a function does not need a name to be created. Though it is far more useful to actually bind it to a name just like any other value.

But like any other value, you sometimes want to use it without binding it to a name. That's the self-invoking pattern.

Here is a function and a number, not bound, they do nothing and can never be used:

function(){ alert("plop"); }
2;

So we have to store them in a variable to be able to use them, just like any other value:

var f = function(){ alert("plop"); }
var n = 2;

You can also use syntatic sugar to bind the function to a variable:

function f(){ alert("plop"); }
var n = 2;

But if naming them is not required and would lead to more confusion and less readability, you could just use them right away.

(function(){ alert("plop"); })(); // will display "plop"
alert(2 + 3); // will display 5

Here, my function and my numbers are not bound to a variable, but they can still be used.

Said like this, it looks like self-invoking function have no real value. But you have to keep in mind that JavaScript scope delimiter is the function and not the block ({}).

So a self-invoking function actually has the same meaning as a C++, C# or Java block. Which means that variable created inside will not "leak" outside the scope. This is very useful in JavaScript in order not to pollute the global scope.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vincent Robert
  • 35,564
  • 14
  • 82
  • 119
  • Nice post. What will then happen with the 'function(){ alert("plop"); }' when I did execute it? It will be GC'ed? – palig Jul 16 '09 at 20:57
  • 2
    The function(){ alert("plop"); } instruction just allocates the function but does not execute it nor binds it to a variable. Since the created function is not bound to any variable, it will be quickly GCed. – Vincent Robert Jul 17 '09 at 08:35
  • [This SO thread](http://stackoverflow.com/questions/881515/javascript-namespace-declaration) goes beyond the scope of what we're talking about here, but it explains ways of separating JavaScript namespaces--and includes examples that use self-invoking functions. – hotshot309 Jul 21 '11 at 03:08
19

It's just how JavaScript works. You can declare a named function:

function foo(msg){
   alert(msg);
}

And call it:

foo("Hi!");

Or, you can declare an anonymous function:

var foo = function (msg) {
    alert(msg);
}

And call that:

foo("Hi!");

Or, you can just never bind the function to a name:

(function(msg){
   alert(msg);
 })("Hi!");

Functions can also return functions:

function make_foo() {
    return function(msg){ alert(msg) };
}

(make_foo())("Hi!");

It's worth nothing that any variables defined with "var" in the body of make_foo will be closed over by each function returned by make_foo. This is a closure, and it means that the any change made to the value by one function will be visible by another.

This lets you encapsulate information, if you desire:

function make_greeter(msg){
    return function() { alert(msg) };
}

var hello = make_greeter("Hello!");

hello();

It's just how nearly every programming language but Java works.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jrockway
  • 42,082
  • 9
  • 61
  • 86
8

The code you show,

(function (msg){alert(msg)});
('SO');

consist of two statements. The first is an expression which yields a function object (which will then be garbage collected because it is not saved). The second is an expression which yields a string. To apply the function to the string, you either need to pass the string as an argument to the function when it is created (which you also show above), or you will need to actually store the function in a variable, so that you can apply it at a later time, at your leisure. Like so:

var f = (function (msg){alert(msg)});
f('SO');

Note that by storing an anonymous function (a lambda function) in a variable, your are effectively giving it a name. Hence you may just as well define a regular function:

function f(msg) {alert(msg)};
f('SO');
Stephan202
  • 59,965
  • 13
  • 127
  • 133
7

In summary of the previous comments:

function() {
  alert("hello");
}();

when not assigned to a variable, yields a syntax error. The code is parsed as a function statement (or definition), which renders the closing parentheses syntactically incorrect. Adding parentheses around the function portion tells the interpreter (and programmer) that this is a function expression (or invocation), as in

(function() {
  alert("hello");
})();

This is a self-invoking function, meaning it is created anonymously and runs immediately because the invocation happens in the same line where it is declared. This self-invoking function is indicated with the familiar syntax to call a no-argument function, plus added parentheses around the name of the function: (myFunction)();.

There is a good SO discussion JavaScript function syntax.

Community
  • 1
  • 1
hotshot309
  • 1,718
  • 1
  • 18
  • 20
4

My understanding of the asker's question is such that:

How does this magic work:

(function(){}) ('input')   // Used in his example

I may be wrong. However, the usual practice that people are familiar with is:

(function(){}('input') )

The reason is such that JavaScript parentheses AKA (), can't contain statements and when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.

Source: blog post Immediately-Invoked Function Expression (IIFE)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
laycat
  • 5,381
  • 7
  • 31
  • 46
4

examples without brackets:

void function (msg) { alert(msg); }
('SO');

(this is the only real use of void, afaik)

or

var a = function (msg) { alert(msg); }
('SO');

or

!function (msg) { alert(msg); }
('SO');

work as well. the void is causing the expression to evaluate, as well as the assignment and the bang. the last one works with ~, +, -, delete, typeof, some of the unary operators (void is one as well). not working are of couse ++, -- because of the requirement of a variable.

the line break is not necessary.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • @Bergi on ie11 `delete` works. even with `'use strict';`. this works, too: `delete (3 + 4);` – Nina Scholz Apr 23 '15 at 20:02
  • Ooops, my mistake. "*2) If Type(ref) is not Reference, return true.*" It only throws errors for actual references that are unresolvable. – Bergi Apr 23 '15 at 20:30
3

This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:

alert(
    {foo: "I am foo", bar: "I am bar"}.foo
); // alerts "I am foo"

Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:

Function.prototype.foo = function () {
    return function () {
        alert("foo");
    };
};

var bar = (function () {}).foo();

bar(); // alerts foo

And you know, we don't even have to surround functions with parenthesis in order to execute them. Anyway, as long as we try to assign the result to a variable.

var x = function () {} (); // this function is executed but does nothing

function () {} (); // syntax error

One other thing you may do with functions, as soon as you declare them, is to invoke the new operator over them and obtain an object. The following are equivalent:

var obj = new function () {
    this.foo = "bar";
};

var obj = {
    foo : "bar"
};
Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
3

There is one more property JavaScript function has. If you want to call same anonymous function recursively.

(function forInternalOnly(){

  //you can use forInternalOnly to call this anonymous function
  /// forInternalOnly can be used inside function only, like
  var result = forInternalOnly();
})();

//this will not work
forInternalOnly();// no such a method exist
xanatos
  • 109,618
  • 12
  • 197
  • 280
Anoop
  • 23,044
  • 10
  • 62
  • 76
  • 2
    +1 Added a small sample so that it's clearer :-) The first time I read it I had to reread 4 times. – xanatos Oct 17 '11 at 06:25
2

It is a self-executing anonymous function. The first set of brackets contain the expressions to be executed, and the second set of brackets executes those expressions.

(function () {
    return ( 10 + 20 );
})();

Peter Michaux discusses the difference in An Important Pair of Parentheses.

It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.

See:

  1. Closure (computer science)
  2. JavaScript Namespacing
  3. Important Pair of Javascript Parentheses
Ashwin Parmar
  • 3,025
  • 3
  • 26
  • 42
1

Another point of view

First, you can declare an anonymous function:

var foo = function(msg){
 alert(msg);
}

Then you call it:

foo ('Few');

Because foo = function(msg){alert(msg);} so you can replace foo as:

function(msg){
 alert(msg);
} ('Few');

But you should wrap your entire anonymous function inside pair of braces to avoid syntax error of declaring function when parsing. Then we have,

(function(msg){
 alert(msg);
}) ('Few');

By this way, It's easy understand for me.

capu
  • 2,245
  • 1
  • 14
  • 11
1

The simple reason why it doesn't work is not because of the ; indicating the end of the anonymous function. It is because without the () on the end of a function call, it is not a function call. That is,

function help() {return true;}

If you call result = help(); this is a call to a function and will return true.

If you call result = help; this is not a call. It is an assignment where help is treated like data to be assigned to result.

What you did was declaring/instantiating an anonymous function by adding the semicolon,

(function (msg) { /* Code here */ });

and then tried to call it in another statement by using just parentheses... Obviously because the function has no name, but this will not work:

('SO');

The interpreter sees the parentheses on the second line as a new instruction/statement, and thus it does not work, even if you did it like this:

(function (msg){/*code here*/});('SO');

It still doesn't work, but it works when you remove the semicolon because the interpreter ignores white spaces and carriages and sees the complete code as one statement.

(function (msg){/*code here*/})        // This space is ignored by the interpreter
('SO');

Conclusion: a function call is not a function call without the () on the end unless under specific conditions such as being invoked by another function, that is, onload='help' would execute the help function even though the parentheses were not included. I believe setTimeout and setInterval also allow this type of function call too, and I also believe that the interpreter adds the parentheses behind the scenes anyhow which brings us back to "a function call is not a function call without the parentheses".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

When you did:

(function (msg){alert(msg)});
('SO');

You ended the function before ('SO') because of the semicolon. If you just write:

(function (msg){alert(msg)})
('SO');

It will work.

Working example: http://jsfiddle.net/oliverni/dbVjg/

Oliver Ni
  • 2,606
  • 7
  • 29
  • 44
1
(function (msg){alert(msg)})
('SO');

This is a common method of using an anonymous function as a closure which many JavaScript frameworks use.

This function called is automatically when the code is compiled.

If placing ; at the first line, the compiler treated it as two different lines. So you can't get the same results as above.

This can also be written as:

(function (msg){alert(msg)}('SO'));

For more details, look into JavaScript/Anonymous Functions.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2349539
  • 161
  • 1
  • 1
  • 7
1

Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they aren’t given a name in the same way as normal functions.

Anonymous functions are declared using the function operator instead of the function declaration. You can use the function operator to create a new function wherever it’s valid to put an expression. For example, you could declare a new function as a parameter to a function call or to assign a property of another object.

Here’s a typical example of a named function:

function flyToTheMoon() {
    alert("Zoom! Zoom! Zoom!"); 
}

flyToTheMoon(); 

Here’s the same example created as an anonymous function:

var flyToTheMoon = function() {
   alert("Zoom! Zoom! Zoom!"); 
}

flyToTheMoon();

For details please read http://helephant.com/2008/08/23/javascript-anonymous-functions/

Robert
  • 7,394
  • 40
  • 45
  • 64
Harikesh Yadav
  • 61
  • 1
  • 1
  • 8
1

The IIFE simply compartmentalizes the function and hides the msg variable so as to not "pollute" the global namespace. In reality, just keep it simple and do like below unless you are building a billion dollar website.

var msg = "later dude";
window.onunload = function(msg){
  alert( msg );
};

You could namespace your msg property using a Revealing Module Pattern like:

var myScript = (function() {
    var pub = {};
    //myscript.msg
    pub.msg = "later dude";
    window.onunload = function(msg) {
        alert(msg);
    };
    //API
    return pub;
}());
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
-1

Anonymous functions are meant to be one-shot deal where you define a function on the fly so that it generates an output from you from an input that you are providing. Except that you did not provide the input. Instead, you wrote something on the second line ('SO'); - an independent statement that has nothing to do with the function. What did you expect? :)

Vietnhi Phuvan
  • 2,704
  • 2
  • 25
  • 25
  • Not 100% correct. This is an anonymous function as well and is meant to be reused: `var foo = function() {};`. Everything else is fine though. – Felix Kling Apr 24 '13 at 06:20