Understanding Anonymous Functions


Anonymous Functions

//An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation.

//Anonymous function declaration

var anon = function() {
    alert('I am anonymous');
};

anon();

// I understand how to declare an anonymous function.


// The most common use for anonymous functions are as arguments to other functions, or as a closure.

setTimeout(function() {
    alert('hello');
}, 1000);

// Our anonymous function is passed to setTimeout, which will execute the function in 1000 milliseconds.

I kinda(wounding mind a refresher on this) understand the anonymous function being use as an argument.


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

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

I’m lose… I don’t understand this technique their using here.


//Breakdown of the above anonymous statements:
//the surrounding braces is a wrapper for the anonymous function
//the trailing braces initiates a call to the function and can contain arguments

(function(message) {
    alert(message);
}('foo'));
// Another way to write the previous example and get the same result

/*An alternative representation of the above places the initiating braces to the surrounding braces and not the function itself, which causes confusion over why the surrounding braces are needed in the first place.*/

What do they mean by wrapper… and everything else???


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

Some have even resorted to giving the trailing braces technique derogatory names, in an effort to encourage people to move them back inside of the surrounding braces to where they initiate the function, instead of the surrounding braces.

Please break it down for me to understand.

Hi,

What is it you don’t understand.
You are passing setTimeout a function which it will execute after the appropriate delay.

You could also write:

function sayHello(){
  alert("Hello");
}

setTimeout(sayHello, 1000);

Does that help?

No it don’t. I don’t understand the syntax. I don’t understand the structure, I don’t understand why is it wrapper in () <– and I don’t understand what is a wrapper. I don’t understand. I’m not talking about what it do, I’m talking about it the structure it self. If all I needed to know what it do, I would have put the code in the console and played with it.

The wrapper is about creating a private scope for variables. JavaScript has only function scope, so if you don’t want your variables to be global, then you need a function in which to put your code.

// This is bad, because x is global
var x = 10;

function myApp() {
    // This is good, because x is locally scoped (not global)
    var x = 10;
}

But the function myApp isn’t being invoked yet. We’d like to invoke it immediately since its only purpose is to provide a variable scope. We can invoke it immediately by putting a pair of parentheses after it like we do when we invoke any function.

// This is bad, because x is global
var x = 10;

function myApp() {
    // This is good, because x is locally scoped (not global)
    var x = 10;
}[COLOR="#FF0000"][SIZE=5]()[/SIZE][/COLOR];

But this isn’t right yet. The above code will produce a syntax error because our function is seen as a function declaration rather than a function expression. (We can immediately invoke an expression but not a declaration.) In order to make the function into an expression, we need to start the statement with some kind of operator. There are several that will work, but the prevailing convention is to wrap the function declaration in parentheses to make it an expression.

// This is bad, because x is global
var x = 10;

[COLOR="#FF0000"][SIZE=5]([/SIZE][/COLOR]function myApp() {
    // This is good, because x is locally scoped (not global)
    var x = 10;
}()[COLOR="#FF0000"][SIZE=5])[/SIZE][/COLOR];

And there you have an immediately invoked function expression.

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

is an anonymous self executing function.

Since named functions in JavaScript are defined starting with the word “function” when a statement starts with the word function JavaScript assumes you are intending to define a named function. To make it anonymous you need to put something in front of the word function. The two common ways to do this are either to place a ! in front of the word function or to wrap the whole function in () - the example uses this second approach.

A self executing function is one that has () added on the end - that makes it run straight away after it has been defined.

To use an anonymous function you either need to assign it to something (a variable or event handler) or execute it immediately after defining it as there is no way to reference it to run it later.

So to split the above into pieces:

function () {
   // ...
}

This part is the definition of the anonymous function but it is not a complete statement as a statement that starts with function can’t be anonymous.

(function () {
   // ...
})

Now we have wrapped the anonymous function in () so that it can be a complete statement - although as it is anonymous there is no way to reference it from elsewhere in the code.

(function () {
   // ...
})()

Adding the () on the end runs the function straight away once it has been defined.

This is done in JavaScript because everything declared inside of a function is local in scope to that function. The effect of wrapping any JavaScript code inside of this self executing function wrapper is to take all of the variables it defines out of the global scope and make them local to that anonymous function. That allows you to easily add multiple scripts to the same page without worrying about whether they use the same variable names - which would cause the scripts to interfere with one another if those variables were global.


(function myApp() {        //a recursive function invoke itself... it this a recursive function? 
    var x = 10;
alert(x);
}());

function myApp() {
    var x = 10;
alert(x);
};

(function(message) {
    alert(message);
}('foo'));

So this is a recursive? by definition, or what I study so far from varies tutorials, a recursive is a function that invoke itself.

And as felgall describe, a function can’t be null of a name, even know it is anonymous, but by that I mean, it must at least either have a variable to reference it, or as you describe, must be wrap in () follow by () to invoke it… is this correct. If so, please yes or no with a follow explanations on it more. So I can grasp the full concept understanding of this.

It’s not recursive, no. Strictly speaking, the function isn’t invoking itself. We are invoking it. That we choose to invoke it immediately isn’t the same as saying the function invoked itself.

First off, thanks for he break down. Second off, you said(please look above for code block that contain comments). I like your explanation… Note that I might change this comment. I want to reread over this to study it.

Could you explain to me a recursive function, and give a example please. I want to understand. And what would is this type of function that goes off as soon as(I’m guessing) the page load, or we enter it into the console.

First of, thanks for the break down.

What good is a ! in front of it?

You mean by executing it immediately as in wrapping it in () with a pair of () following behind it? Precise clarity please

but by the variable being in a function in the first place already make it a local variable.