What is the difference between these 2 JavaScript declarations? - javascript

For one of them the "()" is inside, for the other one it is outside. Here they are:
var a = (function() {
return {
bla: function() {
console.log('a');
}
};
} () );
var b = (function() {
return {
bla: function() {
console.log('b');
}
};
}) ();
a.bla();
b.bla();

There is no difference.
The [unnecessary] parenthesis are just in different places. The function declaration is already an expression due to where it is located. The parenthesis would make a difference, while still resulting in equivalent code, if the declaration was in a statement context (and ironically they would turn it back into an expression context), which it is not.
The common use of parenthesis in a similar scenario is for self-invoking functions. The parenthesis are required in this case because
function x () { alert("hi!") } ()
is parsed as
function x () { alert("hi!") }; ()
when it appears as a statement -- or "top level element of a block" -- where it is parsed as a "FunctionDeclaration". Thus the following form is often used:
(function () { alert("hi!") })()
This works because function ... is no longer a statement, as above, but an expression (parsed as a "FunctionExpression"), and the expression can continue so the Automatic Semicolon Insertion does not occur as in the previous case. Also note that the function name can be omitted.
However, because in the post the function ... appears in an on the right of an = (in an "AssignmentExpression") it is therefore already in an expression context (is parsed as a "FunctionExpression") and thus no additional parenthesis are needed.
All of these are identical, but I prefer the 2nd form (for consistency within my code):
a = function () {} ()
b = (function () {}) ()
c = (function () {} ())
Happy coding.

There is no real difference. Both work in the same way. If you want to pass JSLint, you will need to use the first pattern, where the invocation parentheses are inside the other set of parentheses. If you don't, you will get the following error:
Move the invocation into the parens that contain the function.
Also note that the first set of parentheses are not required. It will work without them, but again will fail JSLint:
Wrap an immediate function invocation in parentheses to assist the
reader in understanding that the expression is the result of a
function, and not the function itself.
A couple of related questions:
JSLint error: "Move the invocation into the parens that contain the function"
Solution for JSLint errors

There is no practical difference, it's just a subtle difference in how you make the Javascript engine think of the function as a value.
Using ( function(){} () ); you are causing the function to be a value because a statement can't start with a parenthesis. Using ( function(){} ) (); you are using the parentheses to first evaluate the function as a value, then call it.

I think is the same difference of this:
var myObj = {bla:'blabla'};
var a = (myObj);
var b = myObj;
...no difference :)

the ending brackets mean that : When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself. (taken from here)
So, if you use {}(), the function is immediately executed and the variable is assigned with the function result.
Then if you use ({})(), if there's a function between (), it is executed and the value is assigned to the variable.
They are the same thing if they contain the same functions in my opinion.

Related

Invoking a named function expression

Can I immediately call(invoke) a named function expression without a variable name like this?
var bookingMask = function (ac) {
....
}('.selectDates');
If you really mean "named" function expression, yes, you can do that:
(function bookingMask(ac) {
// ...
})('.selectDates');
Note the () wrapping it. Otherwise, the function keyword would lead the parser to assume that it was the beginning of a function declaration, which you can't directly invoke in that way.
You might want that if you want to use bookingMask inside the function (e.g., recursion).
Live Example:
(function bookingMask(ac) {
console.log("ac is: " + ac); // "ac is: .selectDates"
console.log(typeof bookingMask); // "function"
})('.selectDates');
If you meant bookingMask to be the result of the call, you can do that too:
var bookingMask = (function nameForTheFunctionHere(ac) {
// ...
})('.selectDates');
If you're doing that, since the parser is already expecting an expression as of the function keyword there, you don't need the wrapper (), this is fine:
var bookingMask = function nameForTheFunctionHere(ac) {
// ...
}('.selectDates');
...but I tend to keep them anyway, since it's really easy when reading the code to miss the (...) at the end.
You can also do it without a name (just remove bookingMask above), but you did specifically say "named", so... :-)
(If anyone's wondering why this answer has four downvotes, when I first posted an answer I missed the fact that the OP had mentioned a named function expression, not least because there isn't one in the question. A couple of people were kind enough to let me know so I could fix it. But people were initially voting on the incorrect answer.)
There are 2 different ways of declaring a function, you can either use function declaration or function expression. The 'expression' part means that it is either assigned to a value var func = function cat(){} or you use parentheses to tell the JavaScript engine to go get the value inside and evaluate it as an expression. So the name IFFE, immediately invoked function expression comes from first turning the function into an expression (function(){}) then calling it (function(){})().
So in your case, you do not want to evaluate the function 'assigning it to a variable' you want to create assign and run the function at once like so...
(function(ac) {
// code...
})('.selectDates');
If your feeling very adventurous you can also use other operators other than the parentheses to evaluate the IFFE such as;
+function IFFE(){
}()
-function IFFE(){
}()

What is the difference between these two Module pattern forms in Javascript? [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 ;-) }

Closure call in JavaScript [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 the difference between these function calls? [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 ;-) }

Is there any difference between putting function call on a self-executing javascript function before or after final 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 ;-) }

Categories