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

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.

Related

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

Why javascript function parentheses can not access the outside? [duplicate]

This question already has answers here:
Why a Name Function Expression not available outside function body [duplicate]
(3 answers)
How do JavaScript closures work?
(86 answers)
Closed 7 years ago.
I'm curious, why not just javascript function scope it? Why just add a parenthesis can not access it? My guess is that the parentheses and javascript related operations, but do not know exactly why this child principle and design?
(function test(){
console.log( test );
})();
test();//Uncaught ReferenceError: test is not defined IE8- is ok
or
(function test(){
console.log( test );
});
test();//Uncaught ReferenceError: test is not defined IE8- is ok
When you wrap a function in parentheses like you did, it does put it in a new scope.
It also acts like a return value, which is why it can be called as an IIFE, or Immediately Invoking Function Expression.
Another way to re-write it, which will make more sense is like so:
var myFunc = (function test(){
alert('Hello!');
});
myFunc(); // Works!
test(); // Doesn't work!
To learn more about this, you should read about IIFE - Immediately-invoked function expression.
The short version - the function runs in its own scope, unless you pass parameters to it, like so:
(function test(x) {
alert(x); //alerts "yey!";
})("yey!");

javascript module pattern implementations [duplicate]

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 9 years ago.
Is there any differences between javascript modules:
(function(){}())
vs
(function(){})()
First from book "good parts" by Crockford.
Second is code generated with Typescript.
There is no different. Also you can write the third option if your function doesn't return any value
!function(){}()
No, there is no difference between those two functions and how they're called. In both cases, you're creating an anonymous function and executing it immediately.
The only reason the "outer" parens are required is that when the JavaScript parser is expecting to see a statement, if it sees function it assumes what follows will be a function declaration. But we want to give a function expression, so by giving it an initial (, we put it into a state where it's expecting an expression.
But where the () to call the function go (after the } or outside the wrapping parens) doesn't make any difference.
No there is no difference, they both work the same. I tend to use the latter... it just seems to make more sense. (function(){}) defines the function and then you call it with (). In either case though, use a (leading)semicolon before the first (. Reference

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

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.

Difference between (function(){})(); and function(){}(); [duplicate]

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

Categories