This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 6 years ago.
I know what auto-running functions are, I use them very often in both Node.js and simple JavaScript. But I still don't understand something.
I kind of know why the following works
(function () {/* Stuff */})();
But I seriously have no idea why the following works...
(function () {/* Stuff */}());
...while the following doesn't...
function () {/* Stuff */}();
...but this also works...
!function () {/* Stuff */}(); // The "!" can be any valid expression
Can I get a detailed explanation?
If it is javascript
(function () {console.log("hi");})();
This is an Immediately invocable function expression, which mean definition followed by invocation, so as it is getting called immediately it works
function () {console.log("hi")}();
This will throw an error ,because definition is followed by braces,if you want to invoke it make it an IIFE
!function () {console.log("hi")}();
This is because, if you put a unary operator before the function declaration, you need not add closing braces, and it chops off one character of the code.
Hope it helps
Related
This question already has answers here:
What does the exclamation mark do before the function?
(8 answers)
Closed 5 years ago.
Sorry for posting this but !function is not google-able and I did not find it in my JavaScript code.
Here is how Twitter uses it:
Tweet
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
from https://twitter.com/about/resources/buttons#
It is short-hand or alternative of self-invoking anonymous function:
(function(){
// code
})();
Can be written:
!function(){
// code
}();
You can also use + instead of !.
If you simply did:
function(){
// code
}();
That will create problems, that's why you need to add ! before it which turns the function declaration into function expression.
Quoting docs, section 12.4:
An ExpressionStatement cannot start with the function keyword because
that might make it ambiguous with a FunctionDeclaration.
To better understand the concept, you should check out:
Function Declarations vs. Function Expressions
they're negating the result, not the function itself:
!function( x ){ return x }( true );
!true
false
In reality, it's a slightly compressed form of:
(function(){}())
since it requires 1 less character. The reason it's needed is that you can't call a function declaration directly, e.g. this is invalid:
function(){}()
but adding the ! at the beginning turns it into a function expression and makes it work.
It's usually used to work around a quirk in the JavaScript syntax. This gives a syntax error:
function() {
}();
It's read as a function declaration (like function foo () {}), rather than a function expression. So adding the ! before it, or wrapping it in parentheses, forces the parser to understand that it's an expression.
This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 6 years ago.
I am learning module pattern in Javascript, and have come across these two ways to create a module:
var Module = (function () {
// code
})();
var Module = (function () {
// code
}());
is there a significant difference in these two approaches? if not, which is considered the better practice? Thanks.
Both are the same. The outer round braces are forcing the inside code to be evaluated as an expression. This means that in both cases the function code is treated as function-expression as well. And then this function is immediately executed due to () braces.
So, it should be exactly the same from the point of view of JS interpreter todo list: 1) get function expression, 2) execute it right away.
It only differs from aesthetic point of view - which way it looks more natural for you.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does the exclamation mark do before the function?
! preceding function in javascript?
javascript function leading bang ! syntax
I've been seeing this pattern a little bit recently in javascript:
!function () {
// do something
}()
what does the bang in front of the function keyword supposed to do? I can't seem to find anything about it on the intertubez.
function () {
// do something
}();
This is an immediately invoked function declaration. A function declaration can not be immediately invoked; it is a syntax error.
To get around this syntax error, most people enclose the IIFD in parens to force it to be an expression instead (IIFE).
(function () {
// do something
})();
In this case, they added an exclamation point instead.
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Why this kind of function invocation is wrong in JavaScript?
Is there any reason to wrap anonymous JavaScript functions in braces?
Is there a good explanation why I have to wrap an anonymous functions in parentheses before I can call it, like this:
(function() { alert('foo'); })();
instead of just
function() { alert('foo'); }();
?
There are other languages in which functions are just things you can pass around, like for example Clojure. In Clojure a function call looks like this: (function args), for example: (+ 1 2). You can just substitute an anonymous function anywhere you would normally use a named function: ((fn [a b] (+ a b)) 1 2). In Javascript this seems not to be the case.
Because without parentheses around the function, the code is a bad function declaration and adding the () to its end is a syntax error.
With parentheses around the function, however, you get a function pointer to an anonymous function which can be executed by adding () to its end.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Are “(function ( ) { } ) ( )” and “(function ( ) { } ( ) )” functionally equal in JavaScript?
This is something I haven't quite figured out yet, but I have been using function(){}() just because my VIM syntax highlight screws up if I add the parenthesis, although I've seen (function(){})() around many times, maybe its an IE thing?
edit:
var singleton = function() {
// code
}();
var singleton = (function() {
// code
})();
Peter Michaux discusses the difference in An Important Pair of Parens.
Basically the parentheses are a convention to denote that an immediately invoked function expression is following, not a plain function. Especially if the function body is lengthy, this reduces surprises,
The extra set of parentheses makes it clearer that you are constructing a function and then calling it. It's a coding style thing, not a functionality thing.
function(){}();
doesn't work in most of browsers. You should use parenthesis around the function in order to execute it
(function(){})();
then browser will know that last parenthesis should be applied to all the expression
function(){}
UPD: If you don't use parenthesis, the brower could misunderstand you. If you just call the function and dismiss the result
function() {
alert(1);
}();
then ff and ie will throw error