Different ways of defining self-executing javascript anonymous functions [duplicate] - javascript

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?

They're virtually the same.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"

In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.
There are other more obviously useful cases for invoking expressions that resolve to functions:
(foo || bar)()

There isn't any difference beyond the syntax.
Regarding your concerns about the second method of doing it:
Consider:
(function namedfunc () { ... }())
namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.
((namedfunc = function namedfunc () { ... })())
The outer parens are unnecessary:
(namedfunc = function namedfunc () { ... })()
But you didn't want that global declaration anyways, did you?
So it it boils down to:
(function namedfunc () { ... })()
And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)
(function () { ... })()
That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.

The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.
The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

Related

Immediately invoked function expression invoking parenthesis [duplicate]

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?
They're virtually the same.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.
There are other more obviously useful cases for invoking expressions that resolve to functions:
(foo || bar)()
There isn't any difference beyond the syntax.
Regarding your concerns about the second method of doing it:
Consider:
(function namedfunc () { ... }())
namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.
((namedfunc = function namedfunc () { ... })())
The outer parens are unnecessary:
(namedfunc = function namedfunc () { ... })()
But you didn't want that global declaration anyways, did you?
So it it boils down to:
(function namedfunc () { ... })()
And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)
(function () { ... })()
That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.
The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.
The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

What is difference between (function(){}()) and (function(){})()? [duplicate]

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?
They're virtually the same.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.
There are other more obviously useful cases for invoking expressions that resolve to functions:
(foo || bar)()
There isn't any difference beyond the syntax.
Regarding your concerns about the second method of doing it:
Consider:
(function namedfunc () { ... }())
namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.
((namedfunc = function namedfunc () { ... })())
The outer parens are unnecessary:
(namedfunc = function namedfunc () { ... })()
But you didn't want that global declaration anyways, did you?
So it it boils down to:
(function namedfunc () { ... })()
And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)
(function () { ... })()
That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.
The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.
The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

Should function call go before or after brackets that wrap function body? [duplicate]

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to wrap an anonymous function in parenthesis and then execute it,
(function () {
// code here
})();
but now it wraps the auto-executed function in parenthesis.
(function () {
// code here
}());
There is a comment by CMS in the accepted answer of Explain JavaScript’s encapsulated anonymous function syntax that “both: (function(){})(); and (function(){}()); are valid.”
I was wondering what the difference is? Does the former take up memory by leaving around a global, anonymous function? Where should the parenthesis be located?
They're virtually the same.
The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.
The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.
I don't think there's a "right" way of doing it, since the result of the expression is the same.
> function(){}()
SyntaxError: Unexpected token (
> (function(){})()
undefined
> (function(){return 'foo'})()
"foo"
> (function(){ return 'foo'}())
"foo"
In that case it doesn't matter. You are invoking an expression that resolves to a function in the first definition, and defining and immediately invoking a function in the second example. They're similar because the function expression in the first example is just the function definition.
There are other more obviously useful cases for invoking expressions that resolve to functions:
(foo || bar)()
There isn't any difference beyond the syntax.
Regarding your concerns about the second method of doing it:
Consider:
(function namedfunc () { ... }())
namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.
((namedfunc = function namedfunc () { ... })())
The outer parens are unnecessary:
(namedfunc = function namedfunc () { ... })()
But you didn't want that global declaration anyways, did you?
So it it boils down to:
(function namedfunc () { ... })()
And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)
(function () { ... })()
That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.
The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.
The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:
+function() {
var foo = 'bar';
}();
!function() {
var foo = 'bar';
}();
-function() {
var foo = 'bar';
}();
~function() {
var foo = 'bar';
}();
And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

Any difference between f() and (f())?

Any difference between
var myfunc = (function () { return function () { ... } }());
and
var myfunc = function () { return function () { ... } }();
Is it just a matter of style or is there more to the surrounding () in the first form?
Nope. Or at least not in your example.
The outer parens only matter when the function keyword would be the first token in a statement.
// cool
var foo = function(){}();
var foo = (function(){}());
// also cool
(function(){}());
// not cool, syntax error
// parsed as function statement, expects function name which is missing
function(){}();
// also not cool, syntax error
// declares a function, but can't be executed immediately
function foo(){}();
When function is the first token in a statement, it's a function declaration (think named function), which behaves slightly differently than function in all other contexts. That leading paren forces the parses to treat it like a function expression (think anonymous function) instead, which allows immediate execution.
See: What is the difference between a function expression vs declaration in JavaScript?
If you start the line or statement with something else, like variable declaration, it technically doesn't matter at all.
No difference, though Crockford advises the use of the former, to ascertain that it's being treated as a function expression.
For more info, read these:
Immediately-Invoked Function Expression (IIFE)
Named function expressions demystified
There's no technical difference, It's just an idiomatic style used for readability to signal at the start that it's a self-invoking function.
no difference, it is just a matter of style. Both are executed functions and they return whatever they return in the variable and they are returning a function. check this out
the purpose is to avoid the global scope, adding the var myfunc = in front of (function (){ return function(){}}()); essentially defeats the purpose
compare the two
(function(){...do something...}());
this function is ran in a local scope, which is inside the parentheses.
var myfunc = function(){};
this function is ran on the global scope.
why not this way, because you can get your self into naming conflicts with other methods and var as well as plugin's named var and it can hinder your applications performance with the var being saved on the global scope.
I perfer
(function() {})();

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