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

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?

Related

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 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).

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.

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.

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