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

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.

Related

Calling an immediately invoked function expression (IIFE) in Javascript [duplicate]

This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
strange observation on IIFE in node.js (Windows)
(2 answers)
Closed 15 days ago.
In Javascript, I can define and call an IIFE as such:
(function() {
console.log("foo");
})();
As I understand it, this defines an anonymous function (thus the parentheses surrounding the function definition) and then immediately invokes it (thus the following parentheses, ()).
I noticed that the following also produces the same result:
(function() {
console.log("foo");
}());
Why is that? If I were to skip the parentheses surrounding the entire definition, it would cause an error:
function() {
console.log("foo");
}();
This results in SyntaxError: Function statements require a function name. How does the interpreter understand the second definition and why does it work?

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.

Javascript Unrecognized Syntax [duplicate]

This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
How does this JavaScript/jQuery syntax work: (function( window, undefined ) { })(window)?
(5 answers)
Closed 9 years ago.
I don't understand what the last line of code is doing here. It looks like random parenthesis tagged at the end of the function. I don't understand the syntax.
(function (self, $, undefined) {
self.methodName = function () {
//do stuff
}
})(This.IsTheNameOf.MyJsFile, Jquery);
What I do know: self = namespace organization tool. $ = JQuery. The first thing in the last line of code is the name of the JS file that contains this code. The last line obviously isn't a function call, but it seems to coincide with self and $.
Any knowledge is greatly appreciated!
Leaving out some stuff we have
function (self, $, undefined) {
// ...
}
So, basically, a function (though a name is missing). Now this gets wrapped in
(/* above code here */)(...);
This is a so-called IIFE (Immediately-Invoked Function Expression). In other words: The function is created and immediately invoked. The reason for this is that it creates a scope in which you can have "private" variables. Also, jQuery gets aliased to $ inside that scope for easy reference. Similarly, This.IsTheNameOf.MyJsFile gets aliased to self.
If you look closely, the function expects three arguments, but is only called with two. This forces the last argument to be (the native) undefined, which happens to be the name of that parameter inside the IIFE. This ensures that undefined, inside that scope, has the expected value (older browsers allowed to overwrite it).

What means construction (function () { ... } ) () [duplicate]

This question already has answers here:
What is this practice called in JavaScript?
(7 answers)
Closed 9 years ago.
What means this construction in JavaScript :
(function (){
alert("bla");
})();
?
The acronym for this pattern is an "IIFE" or an Immediately Invoked Function Expression.
It basically creates an anonymous function function(){}
function(){alert("bla");}
then wraps it as an expression ()
(function(){alert("bla");})
then executes it ()
(function(){alert("bla");})()
Note that at this point, you can pass arguments in as well like this:
(function(text){alert(text);})("bla")
It's an anonymous block - declare an anonymous function then execute it immediately, meaning that any variables declared in the block are not seen outside it. In this case with the alert() it makes no difference.
It is an anonymous function which will be excecuted one time automatically after loading
JS function definition : meaning of the last parentheses
Here you define an anonymous function to be executed immediately.
The function declaration is expressed as a function expression, which may be anonymous and returns the value of the newly created function. It returns the value of the newly created function, so by adding parenthesis after it, you may immediately invoke it.
You define a an anonymous function, which you immediately call.
See also What is the purpose of a self executing function in javascript? for an explanation of the purpose of the construct, which is, in short, to keep names private to the code wrapped in the anonymous function.

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.

Categories