Explain the encapsulated anonymous function syntax - javascript

Summary
Can you explain the reasoning behind the syntax for encapsulated anonymous functions in JavaScript? Why does this work: (function(){})(); but this doesn't: function(){}();?
What I know
In JavaScript, one creates a named function like this:
function twoPlusTwo(){
alert(2 + 2);
}
twoPlusTwo();
You can also create an anonymous function and assign it to a variable:
var twoPlusTwo = function(){
alert(2 + 2);
};
twoPlusTwo();
You can encapsulate a block of code by creating an anonymous function, then wrapping it in brackets and executing it immediately:
(function(){
alert(2 + 2);
})();
This is useful when creating modularised scripts, to avoid cluttering up the current scope, or global scope, with potentially conflicting variables - as in the case of Greasemonkey scripts, jQuery plugins, etc.
Now, I understand why this works. The brackets enclose the contents and expose only the outcome (I'm sure there's a better way to describe that), such as with (2 + 2) === 4.
What I don't understand
But I don't understand why this does not work equally as well:
function(){
alert(2 + 2);
}();
Can you explain that to me?

It doesn't work because it is being parsed as a FunctionDeclaration, and the name identifier of function declarations is mandatory.
When you surround it with parentheses it is evaluated as a FunctionExpression, and function expressions can be named or not.
The grammar of a FunctionDeclaration looks like this:
function Identifier ( FormalParameterListopt ) { FunctionBody }
And FunctionExpressions:
function Identifieropt ( FormalParameterListopt ) { FunctionBody }
As you can see the Identifier (Identifieropt) token in FunctionExpression is optional, therefore we can have a function expression without a name defined:
(function () {
alert(2 + 2);
}());
Or named function expression:
(function foo() {
alert(2 + 2);
}());
The Parentheses (formally called the Grouping Operator) can surround only expressions, and a function expression is evaluated.
The two grammar productions can be ambiguous, and they can look exactly the same, for example:
function foo () {} // FunctionDeclaration
0,function foo () {} // FunctionExpression
The parser knows if it's a FunctionDeclaration or a FunctionExpression, depending on the context where it appears.
In the above example, the second one is an expression because the Comma operator can also handle only expressions.
On the other hand, FunctionDeclarations could actually appear only in what's called "Program" code, meaning code outside in the global scope, and inside the FunctionBody of other functions.
Functions inside blocks should be avoided, because they can lead an unpredictable behavior, e.g.:
if (true) {
function foo() {
alert('true');
}
} else {
function foo() {
alert('false!');
}
}
foo(); // true? false? why?
The above code should actually produce a SyntaxError, since a Block can only contain statements (and the ECMAScript Specification doesn't define any function statement), but most implementations are tolerant, and will simply take the second function, the one which alerts 'false!'.
The Mozilla implementations -Rhino, SpiderMonkey,- have a different behavior. Their grammar contains a non-standard Function Statement, meaning that the function will be evaluated at run-time, not at parse time, as it happens with FunctionDeclarations. In those implementations we will get the first function defined.
Functions can be declared in different ways, compare the following:
1- A function defined with the Function constructor assigned to the variable multiply:
var multiply = new Function("x", "y", "return x * y;");
2- A function declaration of a function named multiply:
function multiply(x, y) {
return x * y;
}
3- A function expression assigned to the variable multiply:
var multiply = function (x, y) {
return x * y;
};
4- A named function expression func_name, assigned to the variable multiply:
var multiply = function func_name(x, y) {
return x * y;
};

Even though this is an old question and answer, it discusses a topic that to this day throws many developers for a loop. I can't count the number of JavaScript developer candidates I've interviewed who couldn't tell me the difference between a function declaration and a function expression and who had no clue what an immediately invoked function expression is.
I'd like to mention, though, one very important thing which is that Premasagar's code snippet wouldn't work even if he had given it a name identifier.
function someName() {
alert(2 + 2);
}();
The reason this wouldn't work is that the JavaScript engine interprets this as a function declaration followed by a completely unrelated grouping operator that contains no expression, and grouping operators must contain an expression. According to JavaScript, the above snippet of code is equivalent to the following one.
function someName() {
alert(2 + 2);
}
();
Another thing I'd like to point out that may be of some use to some people is that any name identifier you provide for a function expression is pretty much useless in the context of the code except from within the function definition itself.
var a = function b() {
// do something
};
a(); // works
b(); // doesn't work
var c = function d() {
window.setTimeout(d, 1000); // works
};
Of course, using name identifiers with your function definitions is always helpful when it comes to debugging code, but that's something else entirely... :-)

Great answers have already being posted. But I want to note that function declarations return an empty completion record:
14.1.20 - Runtime Semantics: Evaluation
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
Return NormalCompletion(empty).
This fact is not easy to observe, because most ways of attempting to get the returned value will convert the function declaration to a function expression. However, eval shows it:
var r = eval("function f(){}");
console.log(r); // undefined
Calling an empty completion record makes no sense. That's why function f(){}() can't work. In fact the JS engine does not even attempt to call it, the parentheses are considered part of another statement.
But if you wrap the function in parentheses, it becomes a function expression:
var r = eval("(function f(){})");
console.log(r); // function f(){}
Function expressions return a function object. And therefore you can call it: (function f(){})().

In javascript, this is called Immediately-Invoked Function Expression (IIFE) .
In order to make it a function expression you've to:
enclose it using ()
place a void operator before it
assign it to a variable.
Otherwise it will be treated as function definition and then you won't be able to call/invoke it at the same time by the following way:
function (arg1) { console.log(arg1) }();
The above will give you error. Because you can only invoke a function expression immediately.
This can be achieved couple of ways:
Way 1:
(function(arg1, arg2){
//some code
})(var1, var2);
Way 2:
(function(arg1, arg2){
//some code
}(var1, var2));
Way 3:
void function(arg1, arg2){
//some code
}(var1, var2);
way 4:
var ll = function (arg1, arg2) {
console.log(arg1, arg2);
}(var1, var2);
All above will immediately invoke the function expression.

I have just another small remark. Your code will work with a small change:
var x = function(){
alert(2 + 2);
}();
I use the above syntax instead of the more widely spread version:
var module = (function(){
alert(2 + 2);
})();
because I didn't manage to get the indentation to work correctly for javascript files in vim. It seems that vim doesn't like the curly braces inside open parenthesis.

(function(){
alert(2 + 2);
})();
Above is valid syntax because anything passed inside parenthesis is consider as function expression.
function(){
alert(2 + 2);
}();
Above is not valid syntax. Because java script syntax parser looks for function name after function keyword since it doesn't find anything it throws an error.

Perhaps the shorter answer would be that
function() { alert( 2 + 2 ); }
is a function literal that defines an (anonymous) function. An additional ()-pair, which is interpreted as an expression, is not expected at toplevel, only literals.
(function() { alert( 2 + 2 ); })();
is in an expression statement that invokes an anonymous function.

They can be used with parameters-arguments like
var x = 3;
var y = 4;
(function(a,b){alert(a + b)})(x,y)
would result as 7

Those extra parenthesis creates extra anonymous functions between global namespace and anonymous function that contains the code. And in Javascript functions declared inside other functions can only access namespace of parent function that contains them. As there is extra object (anonymious function) between global scope and actual code scoping is not retained.

You can also use it like:
! function() { console.log('yeah') }()
or
!! function() { console.log('yeah') }()
! - negation op converts the fn definition to fn expression, therefore, you can invoke it immediately with (). Same as using 0,fn def or void fn def

Related

In JavaScript, Why function expression needs to be in bracket for calling the function [duplicate]

Summary
Can you explain the reasoning behind the syntax for encapsulated anonymous functions in JavaScript? Why does this work: (function(){})(); but this doesn't: function(){}();?
What I know
In JavaScript, one creates a named function like this:
function twoPlusTwo(){
alert(2 + 2);
}
twoPlusTwo();
You can also create an anonymous function and assign it to a variable:
var twoPlusTwo = function(){
alert(2 + 2);
};
twoPlusTwo();
You can encapsulate a block of code by creating an anonymous function, then wrapping it in brackets and executing it immediately:
(function(){
alert(2 + 2);
})();
This is useful when creating modularised scripts, to avoid cluttering up the current scope, or global scope, with potentially conflicting variables - as in the case of Greasemonkey scripts, jQuery plugins, etc.
Now, I understand why this works. The brackets enclose the contents and expose only the outcome (I'm sure there's a better way to describe that), such as with (2 + 2) === 4.
What I don't understand
But I don't understand why this does not work equally as well:
function(){
alert(2 + 2);
}();
Can you explain that to me?
It doesn't work because it is being parsed as a FunctionDeclaration, and the name identifier of function declarations is mandatory.
When you surround it with parentheses it is evaluated as a FunctionExpression, and function expressions can be named or not.
The grammar of a FunctionDeclaration looks like this:
function Identifier ( FormalParameterListopt ) { FunctionBody }
And FunctionExpressions:
function Identifieropt ( FormalParameterListopt ) { FunctionBody }
As you can see the Identifier (Identifieropt) token in FunctionExpression is optional, therefore we can have a function expression without a name defined:
(function () {
alert(2 + 2);
}());
Or named function expression:
(function foo() {
alert(2 + 2);
}());
The Parentheses (formally called the Grouping Operator) can surround only expressions, and a function expression is evaluated.
The two grammar productions can be ambiguous, and they can look exactly the same, for example:
function foo () {} // FunctionDeclaration
0,function foo () {} // FunctionExpression
The parser knows if it's a FunctionDeclaration or a FunctionExpression, depending on the context where it appears.
In the above example, the second one is an expression because the Comma operator can also handle only expressions.
On the other hand, FunctionDeclarations could actually appear only in what's called "Program" code, meaning code outside in the global scope, and inside the FunctionBody of other functions.
Functions inside blocks should be avoided, because they can lead an unpredictable behavior, e.g.:
if (true) {
function foo() {
alert('true');
}
} else {
function foo() {
alert('false!');
}
}
foo(); // true? false? why?
The above code should actually produce a SyntaxError, since a Block can only contain statements (and the ECMAScript Specification doesn't define any function statement), but most implementations are tolerant, and will simply take the second function, the one which alerts 'false!'.
The Mozilla implementations -Rhino, SpiderMonkey,- have a different behavior. Their grammar contains a non-standard Function Statement, meaning that the function will be evaluated at run-time, not at parse time, as it happens with FunctionDeclarations. In those implementations we will get the first function defined.
Functions can be declared in different ways, compare the following:
1- A function defined with the Function constructor assigned to the variable multiply:
var multiply = new Function("x", "y", "return x * y;");
2- A function declaration of a function named multiply:
function multiply(x, y) {
return x * y;
}
3- A function expression assigned to the variable multiply:
var multiply = function (x, y) {
return x * y;
};
4- A named function expression func_name, assigned to the variable multiply:
var multiply = function func_name(x, y) {
return x * y;
};
Even though this is an old question and answer, it discusses a topic that to this day throws many developers for a loop. I can't count the number of JavaScript developer candidates I've interviewed who couldn't tell me the difference between a function declaration and a function expression and who had no clue what an immediately invoked function expression is.
I'd like to mention, though, one very important thing which is that Premasagar's code snippet wouldn't work even if he had given it a name identifier.
function someName() {
alert(2 + 2);
}();
The reason this wouldn't work is that the JavaScript engine interprets this as a function declaration followed by a completely unrelated grouping operator that contains no expression, and grouping operators must contain an expression. According to JavaScript, the above snippet of code is equivalent to the following one.
function someName() {
alert(2 + 2);
}
();
Another thing I'd like to point out that may be of some use to some people is that any name identifier you provide for a function expression is pretty much useless in the context of the code except from within the function definition itself.
var a = function b() {
// do something
};
a(); // works
b(); // doesn't work
var c = function d() {
window.setTimeout(d, 1000); // works
};
Of course, using name identifiers with your function definitions is always helpful when it comes to debugging code, but that's something else entirely... :-)
Great answers have already being posted. But I want to note that function declarations return an empty completion record:
14.1.20 - Runtime Semantics: Evaluation
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
Return NormalCompletion(empty).
This fact is not easy to observe, because most ways of attempting to get the returned value will convert the function declaration to a function expression. However, eval shows it:
var r = eval("function f(){}");
console.log(r); // undefined
Calling an empty completion record makes no sense. That's why function f(){}() can't work. In fact the JS engine does not even attempt to call it, the parentheses are considered part of another statement.
But if you wrap the function in parentheses, it becomes a function expression:
var r = eval("(function f(){})");
console.log(r); // function f(){}
Function expressions return a function object. And therefore you can call it: (function f(){})().
In javascript, this is called Immediately-Invoked Function Expression (IIFE) .
In order to make it a function expression you've to:
enclose it using ()
place a void operator before it
assign it to a variable.
Otherwise it will be treated as function definition and then you won't be able to call/invoke it at the same time by the following way:
function (arg1) { console.log(arg1) }();
The above will give you error. Because you can only invoke a function expression immediately.
This can be achieved couple of ways:
Way 1:
(function(arg1, arg2){
//some code
})(var1, var2);
Way 2:
(function(arg1, arg2){
//some code
}(var1, var2));
Way 3:
void function(arg1, arg2){
//some code
}(var1, var2);
way 4:
var ll = function (arg1, arg2) {
console.log(arg1, arg2);
}(var1, var2);
All above will immediately invoke the function expression.
I have just another small remark. Your code will work with a small change:
var x = function(){
alert(2 + 2);
}();
I use the above syntax instead of the more widely spread version:
var module = (function(){
alert(2 + 2);
})();
because I didn't manage to get the indentation to work correctly for javascript files in vim. It seems that vim doesn't like the curly braces inside open parenthesis.
(function(){
alert(2 + 2);
})();
Above is valid syntax because anything passed inside parenthesis is consider as function expression.
function(){
alert(2 + 2);
}();
Above is not valid syntax. Because java script syntax parser looks for function name after function keyword since it doesn't find anything it throws an error.
Perhaps the shorter answer would be that
function() { alert( 2 + 2 ); }
is a function literal that defines an (anonymous) function. An additional ()-pair, which is interpreted as an expression, is not expected at toplevel, only literals.
(function() { alert( 2 + 2 ); })();
is in an expression statement that invokes an anonymous function.
They can be used with parameters-arguments like
var x = 3;
var y = 4;
(function(a,b){alert(a + b)})(x,y)
would result as 7
Those extra parenthesis creates extra anonymous functions between global namespace and anonymous function that contains the code. And in Javascript functions declared inside other functions can only access namespace of parent function that contains them. As there is extra object (anonymious function) between global scope and actual code scoping is not retained.
You can also use it like:
! function() { console.log('yeah') }()
or
!! function() { console.log('yeah') }()
! - negation op converts the fn definition to fn expression, therefore, you can invoke it immediately with (). Same as using 0,fn def or void fn def

Why are the parentheses around the function AND the argument list? [duplicate]

I would like to know what this means:
(function () {
})();
Is this basically saying document.onload?
It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.
It has nothing to do with any event-handler for any events (such as document.onload).
Consider the part within the first pair of parentheses: (function(){})();....it is a regular function expression. Then look at the last pair (function(){})();, this is normally added to an expression to call a function; in this case, our prior expression.
This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.
This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:
(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// ...
})();
// foo is unreachable here (it’s undefined)
Correction suggested by Guffa:
The function is executed right after it's created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn't automatically mean that it's executed, if for example the IIFE is inside a function then it won't be executed until the function is called.
Update
Since this is a pretty popular topic, it's worth mentioning that IIFE's can also be written with ES6's arrow function (like Gajus has pointed out in a comment) :
((foo) => {
// do something with foo here foo
})('foo value')
It's just an anonymous function that is executed right after it's created.
It's just as if you assigned it to a variable, and used it right after, only without the variable:
var f = function () {
};
f();
In jQuery there is a similar construct that you might be thinking of:
$(function(){
});
That is the short form of binding the ready event:
$(document).ready(function(){
});
But the above two constructs are not IIFEs.
An immediately-invoked function expression (IIFE) immediately calls a function. This simply means that the function is executed immediately after the completion of the definition.
Three more common wordings:
// Crockford's preference - parens on the inside
(function() {
console.log('Welcome to the Internet. Please follow me.');
}());
//The OPs example, parentheses on the outside
(function() {
console.log('Welcome to the Internet. Please follow me.');
})();
//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
console.log('Welcome to the Internet. Please follow me.');
}();
If there are no special requirements for its return value, then we can write:
!function(){}(); // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}(); // => NaN
Alternatively, it can be:
~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();
You can even write:
new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required
That construct is called an Immediately Invoked Function Expression (IIFE) which means it gets executed immediately. Think of it as a function getting called automatically when the interpreter reaches that function.
Most Common Use-case:
One of its most common use cases is to limit the scope of a variable made via var. Variables created via var have a scope limited to a function so this construct (which is a function wrapper around certain code) will make sure that your variable scope doesn't leak out of that function.
In following example, count will not be available outside the immediately invoked function i.e. the scope of count will not leak out of the function. You should get a ReferenceError, should you try to access it outside of the immediately invoked function anyway.
(function () {
var count = 10;
})();
console.log(count); // Reference Error: count is not defined
ES6 Alternative (Recommended)
In ES6, we now can have variables created via let and const. Both of them are block-scoped (unlike var which is function-scoped).
Therefore, instead of using that complex construct of IIFE for the use case I mentioned above, you can now write much simpler code to make sure that a variable's scope does not leak out of your desired block.
{
let count = 10;
}
console.log(count); // ReferenceError: count is not defined
In this example, we used let to define count variable which makes count limited to the block of code, we created with the curly brackets {...}.
I call it a “Curly Jail”.
It declares an anonymous function, then calls it:
(function (local_arg) {
// anonymous function
console.log(local_arg);
})(arg);
That is saying execute immediately.
so if I do:
var val = (function(){
var a = 0; // in the scope of this function
return function(x){
a += x;
return a;
};
})();
alert(val(10)); //10
alert(val(11)); //21
Fiddle: http://jsfiddle.net/maniator/LqvpQ/
Second Example:
var val = (function(){
return 13 + 5;
})();
alert(val); //18
(function () {
})();
This is called IIFE (Immediately Invoked Function Expression). One of the famous JavaScript design patterns, it is the heart and soul of the modern day Module pattern. As the name suggests it executes immediately after it is created. This pattern creates an isolated or private scope of execution.
JavaScript prior to ECMAScript 6 used lexical scoping, so IIFE was used for simulating block scoping. (With ECMAScript 6 block scoping is possible with the introduction of the let and const keywords.)
Reference for issue with lexical scoping
Simulate block scoping with IIFE
The performance benefit of using IIFE’s is the ability to pass commonly used global objects like window, document, etc. as an argument by reducing the scope lookup. (Remember JavaScript looks for properties in local scope and way up the chain until global scope). So accessing global objects in local scope reduces the lookup time like below.
(function (globalObj) {
//Access the globalObj
})(window);
This is an Immediately Invoked Function Expression in Javascript:
To understand IIFE in JS, lets break it down:
Expression: Something that returns a value
Example: Try out following in chrome console. These are expressions in JS.
a = 10
output = 10
(1+3)
output = 4
Function Expression:
Example:
// Function Expression
var greet = function(name){
return 'Namaste' + ' ' + name;
}
greet('Santosh');
How function expression works:
- When JS engine runs for the first time (Execution Context - Create Phase), this function (on the right side of = above) does not get executed or stored in the memory. Variable 'greet' is assigned 'undefined' value by the JS engine.
- During execution (Execution Context - Execute phase), the funtion object is created on the fly (its not executed yet), gets assigned to 'greet' variable and it can be invoked using 'greet('somename')'.
3. Immediately Invoked Funtion Expression:
Example:
// IIFE
var greeting = function(name) {
return 'Namaste' + ' ' + name;
}('Santosh')
console.log(greeting) // Namaste Santosh.
How IIFE works:
- Notice the '()' immediately after the function declaration. Every funtion object has a 'CODE' property attached to it which is callable. And we can call it (or invoke it) using '()' braces.
- So here, during the execution (Execution Context - Execute Phase), the function object is created and its executed at the same time
- So now, the greeting variable, instead of having the funtion object, has its return value ( a string )
Typical usecase of IIFE in JS:
The following IIFE pattern is quite commonly used.
// IIFE
// Spelling of Function was not correct , result into error
(function (name) {
var greeting = 'Namaste';
console.log(greeting + ' ' + name);
})('Santosh');
we are doing two things over here.
a) Wrapping our function expression inside braces (). This goes to tell the syntax parser the whatever placed inside the () is an expression (function expression in this case) and is a valid code.
b) We are invoking this funtion at the same time using the () at the end of it.
So this function gets created and executed at the same time (IIFE).
Important usecase for IIFE:
IIFE keeps our code safe.
- IIFE, being a function, has its own execution context, meaning all the variables created inside it are local to this function and are not shared with the global execution context.
Suppose I've another JS file (test1.js) used in my applicaiton along with iife.js (see below).
// test1.js
var greeting = 'Hello';
// iife.js
// Spelling of Function was not correct , result into error
(function (name) {
var greeting = 'Namaste';
console.log(greeting + ' ' + name);
})('Santosh');
console.log(greeting) // No collision happens here. It prints 'Hello'.
So IIFE helps us to write safe code where we are not colliding with the global objects unintentionally.
No, this construct just creates a scope for naming. If you break it in parts you can see that you have an external
(...)();
That is a function invocation. Inside the parenthesis you have:
function() {}
That is an anonymous function. Everything that is declared with var inside the construct will be visible only inside the same construct and will not pollute the global namespace.
That is a self-invoking anonymous function.
Check out the W3Schools explanation of a self-invoking function.
Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started) automatically, without
being called.
Function expressions will execute automatically if the expression is
followed by ().
You cannot self-invoke a function declaration.
This is the self-invoking anonymous function. It is executed while it is defined. Which means this function is defined and invokes itself immediate after the definition.
And the explanation of the syntax is: The function within the first () parenthesis is the function which has no name and by the next (); parenthesis you can understand that it is called at the time it is defined. And you can pass any argument in this second () parenthesis which will be grabbed in the function which is in the first parenthesis. See this example:
(function(obj){
// Do something with this obj
})(object);
Here the 'object' you are passing will be accessible within the function by 'obj', as you are grabbing it in the function signature.
Start here:
var b = 'bee';
console.log(b); // global
Put it in a function and it is no longer global -- your primary goal.
function a() {
var b = 'bee';
console.log(b);
}
a();
console.log(b); // ReferenceError: b is not defined -- *as desired*
Call the function immediately -- oops:
function a() {
var b = 'bee';
console.log(b);
}(); // SyntaxError: Expected () to start arrow function, but got ';' instead of '=>'
Use the parentheses to avoid a syntax error:
(function a() {
var b = 'bee';
console.log(b);
})(); // OK now
You can leave off the function name:
(function () { // no name required
var b = 'bee';
console.log(b);
})();
It doesn't need to be any more complicated than that.
Self-executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The code
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
2
1
By using this syntax you avoid colliding with global variables declared elsewhere in your JavaScript code.
It is a function expression, it stands for Immediately Invoked Function Expression (IIFE). IIFE is simply a function that is executed right after it is created. So insted of the function having to wait until it is called to be executed, IIFE is executed immediately. Let's construct the IIFE by example. Suppose we have an add function which takes two integers as args and returns the sum
lets make the add function into an IIFE,
Step 1: Define the function
function add (a, b){
return a+b;
}
add(5,5);
Step2: Call the function by wrap the entire functtion declaration into parentheses
(function add (a, b){
return a+b;
})
//add(5,5);
Step 3: To invock the function immediatly just remove the 'add' text from the call.
(function add (a, b){
return a+b;
})(5,5);
The main reason to use an IFFE is to preserve a private scope within your function. Inside your javascript code you want to make sure that, you are not overriding any global variable. Sometimes you may accidentaly define a variable that overrides a global variable. Let's try by example. suppose we have an html file called iffe.html and codes inside body tag are-
<body>
<div id = 'demo'></div>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
Well, above code will execute with out any question, now assume you decleard a variable named document accidentaly or intentional.
<body>
<div id = 'demo'></div>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
const document = "hi there";
console.log(document);
</script>
</body>
you will endup in a SyntaxError: redeclaration of non-configurable global property document.
But if your desire is to declear a variable name documet you can do it by using IFFE.
<body>
<div id = 'demo'></div>
<script>
(function(){
const document = "hi there";
this.document.getElementById("demo").innerHTML = "Hello JavaScript!";
console.log(document);
})();
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
Output:
Let's try by an another example, suppose we have an calculator object like bellow-
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
console.log(calculator.add(5,10));
</script>
</body>
Well it's working like a charm, what if we accidently re-assigne the value of calculator object.
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
console.log(calculator.add(5,10));
calculator = "scientific calculator";
console.log(calculator.mul(5,5));
</script>
</body>
yes you will endup with a TypeError: calculator.mul is not a function iffe.html
But with the help of IFFE we can create a private scope where we can create another variable name calculator and use it;
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
var cal = (function(){
var calculator = {
sub:function(a,b){
return a-b;
},
div:function(a,b){
return a/b;
}
}
console.log(this.calculator.mul(5,10));
console.log(calculator.sub(10,5));
return calculator;
})();
console.log(calculator.add(5,10));
console.log(cal.div(10,5));
</script>
</body>
Output:
TL;DR: Expressions can be enclosed in parenthesis, which would conflict with function calling if the expression and block forms of function were combined.
I like counter-examples because they paint a great picture of the logic, and noone else listed any. You might ask, "Why can't the browser see function(){}() and just assume its an expression?" Let's juxtapose the issue with three examples.
var x;
// Here, fibonacci is a block function
function fibonacci(x) {
var value = x < 2 ? x : fibonacci(x-1) + fibonacci(x-2);
if (x === 9) console.log("The " + x + "th fibonacci is: " + value);
return value;
}
(x = 9);
console.log("Value of x: " + x);
console.log("fibonacci is a(n) " + typeof fibonacci);
Observe how things change when we turn the function into an expression.
var x;
// Here, fibonacci is a function expression
(function fibonacci(x) {
var value = x < 2 ? x : fibonacci(x-1) + fibonacci(x-2);
if (x === 9) console.log("The " + x + "th fibonacci is: " + value);
return value;
})
(x = 9);
console.log("Value of x: " + x);
console.log("fibonacci is a(n) " + typeof fibonacci);
The same thing happens when you use the not-operator instead of parenthesis because both operators turn the statement into an expression:
var x;
// Here, fibonacci is a function expression
! function fibonacci(x) {
var value = x < 2 ? x : fibonacci(x-1) + fibonacci(x-2);
if (x === 9) console.log("The " + x + "th fibonacci is: " + value);
return value;
}
(x = 9);
console.log("Value of x: " + x);
console.log("fibonacci is a(n) " + typeof fibonacci);
By turning the function into an expression, it gets executed by the (x = 9) two lines down from it. Thanks to separate behaviors for expression functions and block functions, both examples run fine without ambiguity (specs-wise).
Name Scoping
Another important observation is that named block functions are visible to the entire scope, whereas function expressions are only visible to themselves. In other words, fibonacci is only visible to the last console.log when it is a block in the first example. In all three examples, fibonacci is visible to itself, allowing fibonacci to call itself, which is recursion.
Arrow Functions
Another aspect to the logic is arrow functions. The specs would have had to include arbitrary rules and exceptions for arrow functions if the definitions of block and expression functions were merged together:
function hello() {console.log("Hello World")}
(x) => console.log("hello " + x)
console.log("If you are reading this, no errors occurred");
Although function blocks work fine, function expressions followed by an arrow function produce a syntax error:
! function hello() {console.log("Hello World")}
(x) => console.log("hello " + x)
console.log("If you are reading this, no errors occurred");
Here, it is ambiguous whether the (x) on line two is calling the function on the preceding line or whether it is the function arguments for an arrow function.
Note that arrow functions have been indeed to the ECMAScript standard over the years and were not a factor in the initial design of the language; my point is that a differentiation between expression and block functions helps JavaScript syntax to be a little more logical and coherent.
Self-executing anonymous function. It's executed as soon as it is created.
One short and dummy example where this is useful is:
function prepareList(el){
var list = (function(){
var l = [];
for(var i = 0; i < 9; i++){
l.push(i);
}
return l;
})();
return function (el){
for(var i = 0, l = list.length; i < l; i++){
if(list[i] == el) return list[i];
}
return null;
};
}
var search = prepareList();
search(2);
search(3);
So instead of creating a list each time, you create it only once (less overhead).
It is called IIFE - Immediately Invoked Function Expression. Here is an example to show it's syntax and usage. It is used to scope the use of variables only till the function and not beyond.
(function () {
function Question(q,a,c) {
this.q = q;
this.a = a;
this.c = c;
}
Question.prototype.displayQuestion = function() {
console.log(this.q);
for (var i = 0; i < this.a.length; i++) {
console.log(i+": "+this.a[i]);
}
}
Question.prototype.checkAnswer = function(ans) {
if (ans===this.c) {
console.log("correct");
} else {
console.log("incorrect");
}
}
var q1 = new Question('Is Javascript the coolest?', ['yes', 'no'], 0);
var q2 = new Question('Is python better than Javascript?', ['yes', 'no', 'both are same'], 2);
var q3 = new Question('Is Javascript the worst?', ['yes', 'no'], 1);
var questions = [q1, q2, q3];
var n = Math.floor(Math.random() * questions.length)
var answer = parseInt(prompt(questions[n].displayQuestion()));
questions[n].checkAnswer(answer);
})();
Already many good answers here but here are my 2 cents :p
You can use IIFE (Immediately Invoked Function Expression) for:
Avoiding pollution in the global namespace.
Variables defined in IIFE (or even any normal function) don't overwrite definitions in global scope.
Protecting code from being accessed by outer code.
Everything that you define within the IIFE can be only be accessed within the IIFE. It protects code from being modified by outer code. Only what you explicitly return as the result of function or set as value to outer variables is accessible by outer code.
Avoid naming functions that you don't need to use repeatedly.
Though it's possible to use a named function in IIFE pattern you don't do it as there is no need to call it repeatedly, generally.
For Universal Module Definitions which is used in many JS libraries. Check this question for details.
IIFE is generally used in following fashion :
(function(param){
//code here
})(args);
You can omit the parentheses () around anonymous function and use void operator before anonymous function.
void function(param){
//code here
}(args);
IIFE (Immediately invoked function expression) is a function which executes as soon as the script loads and goes away.
Consider the function below written in a file named iife.js
(function(){
console.log("Hello Stackoverflow!");
})();
This code above will execute as soon as you load iife.js and will print 'Hello Stackoverflow!' on the developer tools' console.
For a Detailed explanation see Immediately-Invoked Function Expression (IIFE)
One more use case is memoization where a cache object is not global:
var calculate = (function() {
var cache = {};
return function(a) {
if (cache[a]) {
return cache[a];
} else {
// Calculate heavy operation
cache[a] = heavyOperation(a);
return cache[a];
}
}
})();
The following code:
(function () {
})();
is called an immediately invoked function expression (IIFE).
It is called a function expression because the ( yourcode ) operator in Javascript force it into an expression. The difference between a function expression and a function declaration is the following:
// declaration:
function declaredFunction () {}
// expressions:
// storing function into variable
const expressedFunction = function () {}
// Using () operator, which transforms the function into an expression
(function () {})
An expression is simply a bunch of code which can be evaluated to a single value. In case of the expressions in the above example this value was a single function object.
After we have an expression which evaluates to a function object we then can immediately invoke the function object with the () operator. For example:
(function() {
const foo = 10; // all variables inside here are scoped to the function block
console.log(foo);
})();
console.log(foo); // referenceError foo is scoped to the IIFE
Why is this useful?
When we are dealing with a large code base and/or when we are importing various libraries the chance of naming conflicts increases. When we are writing certain parts of our code which is related (and thus is using the same variables) inside an IIFE all of the variables and function names are scoped to the function brackets of the IIFE. This reduces chances of naming conflicts and lets you name them more careless (e.g. you don't have to prefix them).
The reason self-evoking anonymous functions are used is they should never be called by other code since they "set up" the code which IS meant to be called (along with giving scope to functions and variables).
In other words, they are like programs that "make classes', at the beginning of program. After they are instantiated (automatically), the only functions that are available are the ones returned in by the anonymous function. However, all the other 'hidden' functions are still there, along with any state (variables set during scope creation).
Very cool.
In ES6 syntax (posting for myself, as I keep landing on this page looking for a quick example):
// simple
const simpleNumber = (() => {
return true ? 1 : 2
})()
// with param
const isPositiveNumber = ((number) => {
return number > 0 ? true : false
})(4)
This function is called self-invoking function. A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked(Called) immediately after its definition. Read more here
What these functions do is that when the function is defined, The function is immediately called, which saves time and extra lines of code(as compared to calling it on a seperate line).
Here is an example:
(function() {
var x = 5 + 4;
console.log(x);
})();
An immediately invoked function expression (IIFE) is a function that's executed as soon as it's created. It has no connection with any events or asynchronous execution. You can define an IIFE as shown below:
(function() {
// all your code here
// ...
})();
The first pair of parentheses function(){...} converts the code inside the parentheses into an expression.The second pair of parentheses calls the function resulting from the expression.
An IIFE can also be described as a self-invoking anonymous function. Its most common usage is to limit the scope of a variable made via var or to encapsulate context to avoid name collisions.
This is a more in depth explanation of why you would use this:
"The primary reason to use an IIFE is to obtain data privacy. Because JavaScript's var scopes variables to their containing function, any variables declared within the IIFE cannot be accessed by the outside world."
http://adripofjavascript.com/blog/drips/an-introduction-to-iffes-immediately-invoked-function-expressions.html
Normally, JavaScript code has global scope in the application. When we declare global variable in it, there is a chance for using the same duplicate variable in some other area of the development for some other purpose. Because of this duplication there may happen some error. So we can avoid this global variables by using immediately invoking function expression , this expression is self-executing expression.When we make our code inside this IIFE expression global variable will be like local scope and local variable.
Two ways we can create IIFE
(function () {
"use strict";
var app = angular.module("myModule", []);
}());
OR
(function () {
"use strict";
var app = angular.module("myModule", []);
})();
In the code snippet above, “var app” is a local variable now.
Usually, we don't invoke a function immediately after we write it in the program.
In extremely simple terms, when you call a function right after its creation, it is called IIFE - a fancy name.

javascript auto execute anonymous function - parenthesis [duplicate]

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?
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.
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.
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
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.
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.
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');
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.
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)
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.
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"
};
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
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:
Closure (computer science)
JavaScript Namespacing
Important Pair of Javascript Parentheses
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.
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/
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".
(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.
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;
}());
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/
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? :)

JavaScript: What is an anonymous function? [duplicate]

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?
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.
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.
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
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.
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.
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');
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.
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)
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.
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"
};
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
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:
Closure (computer science)
JavaScript Namespacing
Important Pair of Javascript Parentheses
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.
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/
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".
(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.
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;
}());
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/
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? :)

Purpose of the outer extra parenthese on JavaScript closure function [duplicate]

This question already has answers here:
JavaScript - self-executing anonymous functions and callback
(2 answers)
Closed 9 years ago.
What is the purpose of the outer extra parentheses on the below JavaScript closure function? I have been told in other posts that they are not strictly necessary, but they're a convention to make it clear that the result of the function is being passed, not the function itself. The below quote from http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
, however, conflicts. Which is correct?
Notice the () around the anonymous function. This is required by the
language, since statements that begin with the token function are
always considered to be function declarations. Including () creates a
function expression instead.
(function () {
// ... all vars and functions are in this scope only
// still maintains access to all globals
}());
I think that different engines have different ways of interpreting
function(){...}();
so the most popular and accepted way to make it clear, to all engines, is to group the code in parentheses.
(function(){...}());
At the same time, what you quoted makes a very interesting point. A function expression might go:
var f = function() {...}
Whereas a function declaration looks like:
function f() {...}
You see how it's easy/convenient for the parser to tell the difference by looking at the first token?
IF TOKEN1 EQ "function": FXN DECLARATION
ELSE: FXN EXPRESSION
But it wouldn't make sense for your (immediately-invoked) function to be a function declaration (it's not going to be re-used, you don't want to have it hoisted, or in the namespace, etc.) so adding some innocuous parentheses is a good way of indicating that it's a function expression.
First of all, I must clear up:
(function () {
}());
is equivalent for
(function () {
})();
and also for (Backbone.js uses it)
(function(){
}).call(this);
Second, if you're going to use it that way, then it's not an anonymous/closure function. its Immediately-Invoked Function expression
it would act as a closure (because it won't be immediately-invoked) if you assign its returned context to a variable. This kinda useful if you need a static class (when properties and methods could be accessed without instantiation). For example:
var stuff = (function(){
// AGAIN: its not an IIFE in this case
function foo() // <- public method
{
alert('Jeeez');
}
return {
foo : foo,
}
})();
stuff.foo(); //Alerts Jeeez
What is the purpose of the outer extra parentheses on the below
JavaScript closure function?
The purpose isn't usual and quite strange - its all about function arguments.
For example,
(function(window, document){ // <- you see this? 2 "arguments"
alert(arguments.length); // 0!
})();
but if we pass them to that outer parentheses
(function(/* So its not for arguments */ ){
alert(arguments.length); // 2
})(window, document); // <- Instead we pass arguments here
The extra surrounding parentheses disambiguate a function expression from a regular function declaration.
Though the extra parentheses are standard practice, the same thing can be achieved by doing this instead:
void function() {
// do stuff
}();
Or, even:
+function() {
// do stuff
}();
Though, out of these two alternatives, I prefer the void notation because in most cases we don't really care about the return value of an immediate invocation.
Other places where the parentheses aren't required is when an expression is expected:
setTimeout(function() {
return function() {
alert('hello');
}
}(), 1000);
They are necessary because the parser goes in the function declaration mode when it sees
function
in a statement context.
After function token, it is expecting a name for the function because a function declaration must include a name for the function. But instead of a name it sees ( instead, so it's a syntax error.
I think, it could backtrack and unambiguously just treat it as a function expression but it doesn't.
var module = XXX
In the above, XXX is in expression context, if a function appears there, it is treated as a start of a function expression. Function expressions don't have to have
a name for the function, so it's not a syntax error to have ( appear right after function.
So you can write:
var module = function(){}();
But not
function(){}()
You can use many tricks to make the above an expression:
(XXX)
!XXX
~XXX
+XXX
//This doesn't work however:
{YYY} //the braces are delimiting a block, and inside block you start in
//a statement context
XXX is in expression context because it's enclosed by parenthesis or is following a unary operator, therefore any function substituted for XXX is a function expression.

Categories

Resources