What does "!function () {}" mean/do in javascript? [duplicate] - javascript

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.

Related

Meaning of !function in Javascript self invoking function [duplicate]

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.

Confusion about auto-run functions [duplicate]

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

anonymous javascript function call !function vs function [duplicate]

This question already has answers here:
Javascript anonymous function call [duplicate]
(4 answers)
Closed 9 years ago.
How come
function(){ alert("test123");}()
produces SyntaxError: Unexpected token (
while
!function(){ alert("test123");}()
alerts "test123"
?
It's because by adding ! sign you convert the declaration into an expression and invoke it immediately.
By enclosing your function into brackets you will make first example working without errors:
(function(){ alert("test123");})()
To make it clearer you can think about first expression as something like:
if (false || !function(){ return false; }())
And as #zerkms noticed there is a complete explanation of Immediately-invoking functions.

javascript self executing syntax [duplicate]

This question already has answers here:
What does the exclamation mark do before the function?
(8 answers)
Why use NOT operator on anonymous function call? (a la Knockout 2.1.0) [duplicate]
(2 answers)
Closed 9 years ago.
Did anyone know the code which define like this:
!function(window, undefined) {
// do something
} (window)
By searching in google, I can understand the syntax like:
function(window, undefined) {
// do something
} (window)
But I don't figure out any article about the syntax have "!" operator.
The ! operator is there so the function is parsed as an expression, rather than a declaration. Since a declaration cannot be invoked, your second example is a syntax error.
A more commonly seen form is to enclose the function in parentheses:
(function(window,undefined) {
// do something
}(window));
That has exactly the same effect, as does the use of any unary operator.
It might be like this.
!(function(window, undefined){ /* some code */ })(window);
(function(window, undefined){ /* some code */ })(window);

JavaScript immediate function invocation - why are parenthesis needed around the function? [duplicate]

This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 10 years ago.
Why does a function declaration need to be wrapped in parentheses to be immediately invoked? I'm curious as to how the interpreter reads the immediately invoked function when wrapped in parentheses.
I.e.
Why must I do this...
(function() {
// Logic
})();
and not this...
function() {
// Logic
}();
When a function is wrapped in parenthesis it's parsed as an expression - a function expression. Otherwise without them it's parsed as a function declaration. A function declaration requires a name which it sees you have not given it, which in turn causes a syntax error. Moreover, you can't apply () inline to a function declaration in order to call it. The empty parenthesis is a syntax error, but a non-empty parenthesis is an expression which will be evaluated separately from the function.

Categories