This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 8 years ago.
In the YUI library examples, you can find many uses of this construct:
(function() {
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event,
layout = null,
...
})();
I think the last couple of parentheses are to execute the function just after the declaration.
... But what about the previous set of parentheses surrounding the function declaration?
I think it is a matter of scope; that's to hide inside variables to outside functions and possibly global objects. Is it? More generally, what are the mechanics of those parentheses?
It is a self-executing anonymous function. The first set of parentheses contain the expressions to be executed, and the second set of parentheses executes those expressions.
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:
http://en.wikipedia.org/wiki/Closure_%28computer_science%29
http://peter.michaux.ca/articles/javascript-namespacing
Andy Hume pretty much gave the answer, I just want to add a few more details.
With this construct you are creating an anonymous function with its own evaluation environment or closure, and then you immediately evaluate it. The nice thing about this is that you can access the variables declared before the anonymous function, and you can use local variables inside this function without accidentally overwriting an existing variable.
The use of the var keyword is very important, because in JavaScript every variable is global by default, but with the keyword you create a new, lexically scoped variable, that is, it is visible by the code between the two braces. In your example, you are essentially creating short aliases to the objects in the YUI library, but it has more powerful uses.
I don't want to leave you without a code example, so I'll put here a simple example to illustrate a closure:
var add_gen = function(n) {
return function(x) {
return n + x;
};
};
var add2 = add_gen(2);
add2(3); // result is 5
What is going on here? In the function add_gen you are creating an another function which will simply add the number n to its argument. The trick is that in the variables defined in the function parameter list act as lexically scoped variables, like the ones defined with var.
The returned function is defined between the braces of the add_gen function so it will have access to the value of n even after add_gen function has finished executing, that is why you will get 5 when executing the last line of the example.
With the help of function parameters being lexically scoped, you can work around the "problems" arising from using loop variables in anonymous functions. Take a simple example:
for(var i=0; i<5; i++) {
setTimeout(function(){alert(i)}, 10);
}
The "expected" result could be the numbers from zero to four, but you get four instances of fives instead. This happens because the anonymous function in setTimeout and the for loop are using the very same i variable, so by the time the functions get evaluated, i will be 5.
You can get the naively expected result by using the technique in your question and the fact, that function parameters are lexically scoped. (I've used this approach in an other answer)
for(var i=0; i<5; i++) {
setTimeout(
(function(j) {
return function(){alert(j)};
})(i), 10);
}
With the immediate evaluation of the outer function you are creating a completely independent variable named j in each iteration, and the current value of i will be copied in to this variable, so you will get the result what was naively expected from the first try.
I suggest you to try to understand the excellent tutorial at http://ejohn.org/apps/learn/ to understand closures better, that is where I learnt very-very much.
...but what about the previous round parenteses surrounding all the function declaration?
Specifically, it makes JavaScript interpret the 'function() {...}' construct as an inline anonymous function expression. If you omitted the brackets:
function() {
alert('hello');
}();
You'd get a syntax error, because the JS parser would see the 'function' keyword and assume you're starting a function statement of the form:
function doSomething() {
}
...and you can't have a function statement without a function name.
function expressions and function statements are two different constructs which are handled in very different ways. Unfortunately the syntax is almost identical, so it's not just confusing to the programmer, even the parser has difficulty telling which you mean!
Juts to follow up on what Andy Hume and others have said:
The '()' surrounding the anonymous function is the 'grouping operator' as defined in section 11.1.6 of the ECMA spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf.
Taken verbatim from the docs:
11.1.6 The Grouping Operator
The production PrimaryExpression : ( Expression ) is evaluated as follows:
Return the result of evaluating Expression. This may be of type Reference.
In this context the function is treated as an expression.
A few considerations on the subject:
The parenthesis:
The browser (engine/parser) associates the keyword function with
[optional name]([optional parameters]){...code...}
So in an expression like function(){}() the last parenthesis makes no sense.
Now think at
name=function(){} ; name() !?
Yes, the first pair of parenthesis force the anonymous function to turn into a variable (stored expression) and the second launches evaluation/execution, so ( function(){} )() makes sense.
The utility: ?
For executing some code on load and isolate the used variables from the rest of the page especially when name conflicts are possible;
Replace eval("string") with
(new Function("string"))()
Wrap long code for " =?: " operator like:
result = exp_to_test ? (function(){... long_code ...})() : (function(){...})();
The first parentheses are for, if you will, order of operations. The 'result' of the set of parentheses surrounding the function definition is the function itself which, indeed, the second set of parentheses executes.
As to why it's useful, I'm not enough of a JavaScript wizard to have any idea. :P
See this question. The first set of parenthesis aren't necessary if you use a function name, but a nameless function requires this construct and the parenthesis serve for coders to realize that they've viewing a self-invoking function when browsing the code (see one blogger's best-practices recommendation).
Related
This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 7 years ago.
I'm reading up on JavaScript IIFE and so far the understand concept, but I am wondering about the outside parenthesis. Specifically, why are they required? For example,
(function() {var msg='I love JavaScript'; console.log(msg);}());
works great, but
function() {var msg='I love JavaScript'; console.log(msg);}();
generates a syntax error. Why? There are lots of discussions on IIFE, but I'm not seeing a clear explanation about why the parentheses are required.
There are two ways to create functions in JavaScript (well, 3, but let's ignore new Function()). You can either write a function declaration or write a function expression.
A function declaration in itself is a statement and statements by themselves don't return values (let's also ignore how the debugging console or Node.js REPL print return values of statements). A function expression however is a proper expression and expressions in JavaScript returns values that can be immediately used.
Now, you may have seen people saying that the following is a function expression:
var x = function () {};
It may be tempting to conclude that the syntax:
function () {};
is what makes it an expression. But that's wrong. The syntax above is what makes it an anonymous function. And anonymous functions can either be a declaration or an expression. What makes it an expression is this syntax:
var x = ...
That is, everything to the right of an = sign is an expression. Expressions make it easier to write math formulas in programming languages. So in general everywhere that math is expected to be processed is an expression.
Some of the forms of expressions in JavaScript include:
everything to the right of an = operator
things in braces () that are not function call braces
everything to the right of a math operator (+,-,*,/)
all the arguments to the ternary operator .. ? .. : ..
When you write:
function () {}
it is a declaration and does not return a value (the declared function). Therefore trying to call the non-result is an error.
But when you write:
(function () {})
it is an expression and returns a value (the declared function) which may be used immediately (for example, may be called or may be assigned).
Note the rules for what counts as expressions above. From that it follows that braces are not the only things that you can use to construct an IIFE. Below are valid ways for constructing IIFEs (because we write function expressions):
tmp=function(){}()
+function(){}()
-function(){}()
0/function(){}()
0*function(){}()
0?0:function(){}()
(function(){}())
(function(){})()
You may actually see one of the above non-standard forms (particularly the + version) in third-party libraries, because they want to save one byte. But I strongly advise you to only use the brace forms (either are fine), because they are widely recognized as IIFEs by other programmers.
The version of IIFE that is wrapped in parenthesis works, because this marks the declaration of the internal function declaration as an expression.
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
For more detailed explanation please see:
Advanced JavaScript: Why is this function wrapped in parentheses?
HINT:
The invocation operator (()) only works with expressions, not declarations.
This will be a long-winded answer, but will give you the necessary background. In JavaScript there are two ways functions can be defined:
A function definition (the classical kind)
function foo() {
//why do we always use
}
and then the more obscure type, a function expression
var bar = function() {
//foo and bar
};
In essence the same thing is going on at execution. A function object is created, memory is allocated, and an identifier is bound to the function. The difference is in the syntax. The former is itself a statement which declares a new function, the latter is an expression.
The function expression gives us the ability to insert a function any place where a normal expression would be expected. This lends its way to anonymous functions and callbacks. Take for instance
setTimeout(500, function() {
//for examples
});
Here, the anonymous function will execute whenever setTimeout says so. If we want to execute a function expression immediately, however, we need to ensure the syntax is recognizable as an expression, otherwise we have ambiguity as to whether of not we mean a function expression or statement.
var fourteen = function sumOfSquares() {
var value = 0;
for (var i = 0; i < 4; i++)
value += i * i;
return value;
}();
Here sumOfSquares is immediately invoked because it can be recognized as an expression. fourteen becomes 14 and sumOfSquares is garbage-collected. In your example, the grouping operator () coerces its content into an expression, therefore the function is an expression and can be called immediately as such.
One important thing to note about the difference between my first foo and bar example though is hoisting. If you don't know what that it is, a quick Google search or two should tell you, but the quick and dirty definition is that hoisting is JavaScript's behavior to bring declarations (variables and functions) to the top of a scope. These declarations usually only hoist the identifier but not its initialized value, so the entire scope will be able to see the variable/function before it is assigned a value.
With function definitions this is not the case, here the entire declaration is hoisted and will be visible throughout the containing scope.
console.log("lose your " + function() {
fiz(); //will execute fiz
buzz(); //throws TypeError
function fiz() {
console.log("lose your scoping,");
}
var buzz = function() {
console.log("and win forever");
};
return "sanity";
}()); //prints "lose your scoping, lose your sanity"
There is a JSLint option, one of The Good Parts in fact, that "[requires] parens around immediate invocations," meaning that the construction
(function () {
// ...
})();
would instead need to be written as
(function () {
// ...
}());
My question is this -- can anyone explain why this second form might be considered better? Is it more resilient? Less error-prone? What advantage does it have over the first form?
Since asking this question, I have come to understand the importance of having a clear visual distinction between function values and the values of functions. Consider the case where the result of immediate invocation is the right-hand side of an assignment expression:
var someVar = (function () {
// ...
}());
Though the outermost parentheses are syntactically unnecessary, the opening parenthesis gives an up-front indication that the value being assigned is not the function itself but rather the result of the function being invoked.
This is similar to Crockford's advice regarding capitalization of constructor functions -- it is meant to serve as a visual cue to anyone looking at the source code.
From Douglass Crockford's style convention guide: (search for "invoked immediately")
When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.
So, basically, he feels it makes more clear the distinction between function values, and the values of functions. So, it's an stylistic matter, not really a substantive difference in the code itself.
updated reference, old PPT no longer exists
Immediately Called Anonymous Functions get wrapped it in parens because:
They are function expressions and leaving parens out would cause it to be interpreted as a function declaration which is a syntax error.
Function expressions cannot start with the word function.
When assigning the function expression to a variable, the function itself is not returned, the return value of the function is returned, hence the parens evaluate what's inside them and produce a value. when the function is executed, and the trailing parens ..}() cause the function to execute immediately.
Or, use:
void function () {
...
} ()
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between a function expression vs declaration in Javascript?
Is there a MAJOR difference between declaring functions in these ways:
function foo(){
alert('BAR');
}
var foo = function (){
alert('BAR');
}
var foo = function bar(){
alert('BAR');
}
I was told here that:
It happens at a different time, and results in a variable referring to an anonymous function. A function declaration happens prior to any stepwise code executing in the scope, and results in both a binding and a function with a proper name.
Can the way I declare my function really affect the efficiency of my code, and if so which way is best to use?
Yes, there is a major difference.
The first is a function declaration. It happens upon entry to an execution context, prior to any step-by-step code being processed. It cannot be within any kind of control block (e.g., it's not legal in the body of an if statement; however, most browsers will try to accommodate it if you do that — sometimes resulting in very surprising behavior — at variance with the spec). It results in a named function.
The second is a function expression (specifically, an anonymous function expression). Like all expressions, it's processed when it's encountered in the step-by-step execution of the code. And like all expressions, it can be within a control block. It results in a function with no name assigned to a variable that has a name.
The third is a named function expression. It's a function expression like the above, but the function is also given a name. You want to avoid these with IE8 and earlier, since IE will actually get it quite wrong, creating two separate functions (at two different times). (Basically, IE treats it as both a function declaration and a function expression.) IE9 finally gets this right.
Note that your second and third examples rely on automatic semicolon insertion; because those are both assignment statements, they should end with a ; (after the ending } of the function).
bit of a silly question perhaps.
But I want to understand why the syntax on the self-executing function and the callback it has is so different to all the other JS syntax..
(function () {
})()
I just need to understand why its valid to encapsulate it with () I wouldn't have guessed that to be valid, and then the extra () afterwards for the callback, (which just sits directly after it, I also wouldn't have expected that to be valid.
Is anyone able to explain this to me?
The function (...) {...} part is a function expression, that is, an expression that represents a function. The only reason it has to be wrapped in parentheses in this case is that if the keyword function is the very first thing in a statement, then the statement is assumed to be a function statement, that is, a function declaration. (Actually, it doesn't necessarily have to be wrapped in parentheses; it also works to prefix it with a +, or in general to put any sort of token before function that prevents the function-statement interpretation.)
The () part after the function expression is the same as the normal () for calling a function. This:
(function (...) {...})(...);
is (aside from the temporary variable) the same as this:
var f = function (...) {...};
f();
which is equivalent to this:
function f(...) {...};
f();
Essentially the outer parentheses allow the function object to be fully interpreted and instantiated, so that once you exit the scope of those parentheses the function object is ready to be called.
See here:
Why do you need to invoke an anonymous function on the same line?
When declaring as you did, you are using it as a function expression (3rd way of defining the function from the above link). As with any expression, this (expression) evaluates to expression - parentheses are used here is establish precedence where necessary. So you can write this for example:
var f = function(a) {
var s = (((( 1 )))) + (((( a ))));
console.log(s);
};
((((( f ))))) (2);
(live example) and then remove all the unnecessary parentheses with the same result (which is printing of 1 + 2 = 3, essentially). The result of:
(function(...) { ... })
is a function that accepts some arguments and has a body to be executed. This:
(function(...) { ... })()
is pretty much equivalent to:
var f = (function(...) { ... });
// Now f is a function that can be called
f();
Anonymous functions are useful, among other things, for two reasons - they are anonymous (i.e. they don't create additional names - see again the above SOq link) and they are "containers" for other stuff that doesn't need to be global.
What you have here is an Immediately-invoked function expression also known as IFFE (read iffy) and is a design pattern which produces lexical scope using JS function scoping. These are used to avoid variable hoisting, polluting the global environment and simultaneously allowing public acces to methods while retaining the local privacy of variables declared whithin the function.
The key to understanding this is that JS has function scope and not block scope and passes values by reference inside a closure.
You can read further into this at Immediately-invoked function expression.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
I see functions inside parentheses in jQuery plugins and the like.
For example,
(function(args) {
// ...
})(localVariable);
What does this do, exactly?
You mean something like the following?:
(function() {
// ...
})();
This basically ensures that any "var" declarations are kept private (they are scoped to the anonymous function in which they have been placed) rather than global. For example, consider:
var counter = 0;
window['inc'] = function() {
return counter++;
};
vs.
(function() {
var counter = 0;
window['inc'] = function() {
return counter++;
};
})();
Both of these have the effect of defining a function window.inc that returns a counter that gets incremented; however, in the first version, counter is actually visible to all other modules, because it is in the global scope, whereas the latter ensures that only window.inc can access counter.
Note that the code creates a function and immediately invokes it (that's what the last parens are for).
The unofficial name is an 'immediate function' - the basic idea is that the function is defined and called on the fly.
Here's a simple example:
http://javascriptmountain.com/2011/06/functions/immediate-functions-in-javascript-the-basics/
The parentheses are actually not necessary unless the return value of the function is assigned to a variable, but they are usually used for readability.
The reason it is done in situations like jquery plugins is that it provides a sort of 'sandbox' for executing code. Say we did the following:
(function($) {
// augment $ with methods
}(jQuery));
this defines a function that takes in one parameter, then IMMEDIATELY calls the function, passing in the global jquery object. Any vars that are declared and used inside the immediate function will be locally scoped to the function, and will not interfere with global scope or disrupt any global variables that may have been declared in other pieces of javascript code being used (important for libraries intended to be used with large amounts of other code).
However, since we are passing in the global jquery object when we call the function, we can still add methods and properties to the '$' parameter inside of the function that will hang around on the jquery object after the function completes.
Hope this helps!