Immediately Invoked Function Expression in javascript - javascript

What is the reason of putting ( ) in the end for Immediately Invoked Function Expression in javascript
(function() {
// Code that runs in your function
})( /* this parenthesis in the end */ )

An Immediately Invoked Function Expression is a:
(function() { ... }) ← Function Expression which is Immediately Invoked → ()
To elaborate, (function() { ... }) is merely defining the function, and a function which is defined but never called is doing absolutely nothing.
In order for the code in the function to be executed, it needs to be invoked (often referred to as calling the function). That is why you wrap the function definition in parentheses (making it an expression that evaluates to a reference to the function) and then immediately invoke (or call) the function with any arguments () - or no arguments as in your sample.
It is more or less equivalent to doing this:
const someFunc = (function() { ... }); //merely assigns a function, the code inside doesn't run
someFunc(); //invokes the function (but in this case it isn't immediate)
except in this case you've bound the function reference to a variable and so it is no longer an IIFE.

The reason is purely syntactical. The JavaScript parser has to be able
to easily differentiate between function declarations and function
expressions. If we leave out the parentheses around the function
expression, and put our immediate call as a separate statement
function(){}(3), the JavaScript parser will start processing it, and will conclude, because it’s a separate statement starting with the
key- word function, that it’s dealing with a function declaration.
Because every function declaration has to have a name (and here we
didn’t specify one), an error will be thrown. To avoid this, we place
the function expression within parentheses, signaling to the
JavaScript parser that it’s dealing with an expression, and not a
statement. There’s also an alternative way of achieving the same goal:
(function(){}(3))
By wrapping the immediate function definition and call within
parentheses, you can also notify the JavaScript parser that it’s
dealing with an expression.
Those four expressions are variations of the same theme of
immediately invoked function expressions often found in various
JavaScript libraries:
+function(){}();
-function(){}();
!function(){}();
~function(){}();
This time, instead of using parentheses around the function
expressions to differentiate them from function declarations, we can
use unary operators: + , - , ! , and ~ . We do this to signal to the
JavaScript engine that it’s dealing with expressions and not
statements.
Reference: johnresig.com/

Related

Invoking a named function expression

Can I immediately call(invoke) a named function expression without a variable name like this?
var bookingMask = function (ac) {
....
}('.selectDates');
If you really mean "named" function expression, yes, you can do that:
(function bookingMask(ac) {
// ...
})('.selectDates');
Note the () wrapping it. Otherwise, the function keyword would lead the parser to assume that it was the beginning of a function declaration, which you can't directly invoke in that way.
You might want that if you want to use bookingMask inside the function (e.g., recursion).
Live Example:
(function bookingMask(ac) {
console.log("ac is: " + ac); // "ac is: .selectDates"
console.log(typeof bookingMask); // "function"
})('.selectDates');
If you meant bookingMask to be the result of the call, you can do that too:
var bookingMask = (function nameForTheFunctionHere(ac) {
// ...
})('.selectDates');
If you're doing that, since the parser is already expecting an expression as of the function keyword there, you don't need the wrapper (), this is fine:
var bookingMask = function nameForTheFunctionHere(ac) {
// ...
}('.selectDates');
...but I tend to keep them anyway, since it's really easy when reading the code to miss the (...) at the end.
You can also do it without a name (just remove bookingMask above), but you did specifically say "named", so... :-)
(If anyone's wondering why this answer has four downvotes, when I first posted an answer I missed the fact that the OP had mentioned a named function expression, not least because there isn't one in the question. A couple of people were kind enough to let me know so I could fix it. But people were initially voting on the incorrect answer.)
There are 2 different ways of declaring a function, you can either use function declaration or function expression. The 'expression' part means that it is either assigned to a value var func = function cat(){} or you use parentheses to tell the JavaScript engine to go get the value inside and evaluate it as an expression. So the name IFFE, immediately invoked function expression comes from first turning the function into an expression (function(){}) then calling it (function(){})().
So in your case, you do not want to evaluate the function 'assigning it to a variable' you want to create assign and run the function at once like so...
(function(ac) {
// code...
})('.selectDates');
If your feeling very adventurous you can also use other operators other than the parentheses to evaluate the IFFE such as;
+function IFFE(){
}()
-function IFFE(){
}()

Why are parentheses required around JavaScript IIFE? [duplicate]

This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 7 years ago.
I'm reading up on JavaScript IIFE and so far the understand concept, but I am wondering about the outside parenthesis. Specifically, why are they required? For example,
(function() {var msg='I love JavaScript'; console.log(msg);}());
works great, but
function() {var msg='I love JavaScript'; console.log(msg);}();
generates a syntax error. Why? There are lots of discussions on IIFE, but I'm not seeing a clear explanation about why the parentheses are required.
There are two ways to create functions in JavaScript (well, 3, but let's ignore new Function()). You can either write a function declaration or write a function expression.
A function declaration in itself is a statement and statements by themselves don't return values (let's also ignore how the debugging console or Node.js REPL print return values of statements). A function expression however is a proper expression and expressions in JavaScript returns values that can be immediately used.
Now, you may have seen people saying that the following is a function expression:
var x = function () {};
It may be tempting to conclude that the syntax:
function () {};
is what makes it an expression. But that's wrong. The syntax above is what makes it an anonymous function. And anonymous functions can either be a declaration or an expression. What makes it an expression is this syntax:
var x = ...
That is, everything to the right of an = sign is an expression. Expressions make it easier to write math formulas in programming languages. So in general everywhere that math is expected to be processed is an expression.
Some of the forms of expressions in JavaScript include:
everything to the right of an = operator
things in braces () that are not function call braces
everything to the right of a math operator (+,-,*,/)
all the arguments to the ternary operator .. ? .. : ..
When you write:
function () {}
it is a declaration and does not return a value (the declared function). Therefore trying to call the non-result is an error.
But when you write:
(function () {})
it is an expression and returns a value (the declared function) which may be used immediately (for example, may be called or may be assigned).
Note the rules for what counts as expressions above. From that it follows that braces are not the only things that you can use to construct an IIFE. Below are valid ways for constructing IIFEs (because we write function expressions):
tmp=function(){}()
+function(){}()
-function(){}()
0/function(){}()
0*function(){}()
0?0:function(){}()
(function(){}())
(function(){})()
You may actually see one of the above non-standard forms (particularly the + version) in third-party libraries, because they want to save one byte. But I strongly advise you to only use the brace forms (either are fine), because they are widely recognized as IIFEs by other programmers.
The version of IIFE that is wrapped in parenthesis works, because this marks the declaration of the internal function declaration as an expression.
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
For more detailed explanation please see:
Advanced JavaScript: Why is this function wrapped in parentheses?
HINT:
The invocation operator (()) only works with expressions, not declarations.
This will be a long-winded answer, but will give you the necessary background. In JavaScript there are two ways functions can be defined:
A function definition (the classical kind)
function foo() {
//why do we always use
}
and then the more obscure type, a function expression
var bar = function() {
//foo and bar
};
In essence the same thing is going on at execution. A function object is created, memory is allocated, and an identifier is bound to the function. The difference is in the syntax. The former is itself a statement which declares a new function, the latter is an expression.
The function expression gives us the ability to insert a function any place where a normal expression would be expected. This lends its way to anonymous functions and callbacks. Take for instance
setTimeout(500, function() {
//for examples
});
Here, the anonymous function will execute whenever setTimeout says so. If we want to execute a function expression immediately, however, we need to ensure the syntax is recognizable as an expression, otherwise we have ambiguity as to whether of not we mean a function expression or statement.
var fourteen = function sumOfSquares() {
var value = 0;
for (var i = 0; i < 4; i++)
value += i * i;
return value;
}();
Here sumOfSquares is immediately invoked because it can be recognized as an expression. fourteen becomes 14 and sumOfSquares is garbage-collected. In your example, the grouping operator () coerces its content into an expression, therefore the function is an expression and can be called immediately as such.
One important thing to note about the difference between my first foo and bar example though is hoisting. If you don't know what that it is, a quick Google search or two should tell you, but the quick and dirty definition is that hoisting is JavaScript's behavior to bring declarations (variables and functions) to the top of a scope. These declarations usually only hoist the identifier but not its initialized value, so the entire scope will be able to see the variable/function before it is assigned a value.
With function definitions this is not the case, here the entire declaration is hoisted and will be visible throughout the containing scope.
console.log("lose your " + function() {
fiz(); //will execute fiz
buzz(); //throws TypeError
function fiz() {
console.log("lose your scoping,");
}
var buzz = function() {
console.log("and win forever");
};
return "sanity";
}()); //prints "lose your scoping, lose your sanity"

Immediate functions and different declarative syntaxes [duplicate]

There is a JSLint option, one of The Good Parts in fact, that "[requires] parens around immediate invocations," meaning that the construction
(function () {
// ...
})();
would instead need to be written as
(function () {
// ...
}());
My question is this -- can anyone explain why this second form might be considered better? Is it more resilient? Less error-prone? What advantage does it have over the first form?
Since asking this question, I have come to understand the importance of having a clear visual distinction between function values and the values of functions. Consider the case where the result of immediate invocation is the right-hand side of an assignment expression:
var someVar = (function () {
// ...
}());
Though the outermost parentheses are syntactically unnecessary, the opening parenthesis gives an up-front indication that the value being assigned is not the function itself but rather the result of the function being invoked.
This is similar to Crockford's advice regarding capitalization of constructor functions -- it is meant to serve as a visual cue to anyone looking at the source code.
From Douglass Crockford's style convention guide: (search for "invoked immediately")
When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.
So, basically, he feels it makes more clear the distinction between function values, and the values of functions. So, it's an stylistic matter, not really a substantive difference in the code itself.
updated reference, old PPT no longer exists
Immediately Called Anonymous Functions get wrapped it in parens because:
They are function expressions and leaving parens out would cause it to be interpreted as a function declaration which is a syntax error.
Function expressions cannot start with the word function.
When assigning the function expression to a variable, the function itself is not returned, the return value of the function is returned, hence the parens evaluate what's inside them and produce a value. when the function is executed, and the trailing parens ..}() cause the function to execute immediately.
Or, use:
void function () {
...
} ()

Self-executing function syntax and callback syntax explained

bit of a silly question perhaps.
But I want to understand why the syntax on the self-executing function and the callback it has is so different to all the other JS syntax..
(function () {
})()
I just need to understand why its valid to encapsulate it with () I wouldn't have guessed that to be valid, and then the extra () afterwards for the callback, (which just sits directly after it, I also wouldn't have expected that to be valid.
Is anyone able to explain this to me?
The function (...) {...} part is a function expression, that is, an expression that represents a function. The only reason it has to be wrapped in parentheses in this case is that if the keyword function is the very first thing in a statement, then the statement is assumed to be a function statement, that is, a function declaration. (Actually, it doesn't necessarily have to be wrapped in parentheses; it also works to prefix it with a +, or in general to put any sort of token before function that prevents the function-statement interpretation.)
The () part after the function expression is the same as the normal () for calling a function. This:
(function (...) {...})(...);
is (aside from the temporary variable) the same as this:
var f = function (...) {...};
f();
which is equivalent to this:
function f(...) {...};
f();
Essentially the outer parentheses allow the function object to be fully interpreted and instantiated, so that once you exit the scope of those parentheses the function object is ready to be called.
See here:
Why do you need to invoke an anonymous function on the same line?
When declaring as you did, you are using it as a function expression (3rd way of defining the function from the above link). As with any expression, this (expression) evaluates to expression - parentheses are used here is establish precedence where necessary. So you can write this for example:
var f = function(a) {
var s = (((( 1 )))) + (((( a ))));
console.log(s);
};
((((( f ))))) (2);
(live example) and then remove all the unnecessary parentheses with the same result (which is printing of 1 + 2 = 3, essentially). The result of:
(function(...) { ... })
is a function that accepts some arguments and has a body to be executed. This:
(function(...) { ... })()
is pretty much equivalent to:
var f = (function(...) { ... });
// Now f is a function that can be called
f();
Anonymous functions are useful, among other things, for two reasons - they are anonymous (i.e. they don't create additional names - see again the above SOq link) and they are "containers" for other stuff that doesn't need to be global.
What you have here is an Immediately-invoked function expression also known as IFFE (read iffy) and is a design pattern which produces lexical scope using JS function scoping. These are used to avoid variable hoisting, polluting the global environment and simultaneously allowing public acces to methods while retaining the local privacy of variables declared whithin the function.
The key to understanding this is that JS has function scope and not block scope and passes values by reference inside a closure.
You can read further into this at Immediately-invoked function expression.

self-invoking anonymous function parsing issue

I'm having some trouble understanding how both of these two lines are inter-changeable.
( function() { return console.log("anon inner 1"); } ) ();
// ^^ invoke
( function() { return console.log("anon inner 2"); } () );
// ^^ invoke
In the first line, we have an anonymous inner function that is wrapped in parenthesis, and then immediately invoked. The second line, we have an anonymous inner function that is invoked and then wrapped in parentheses.
I guess my question is, what does the wrapping in parenthesis do? Does it objectify stuff, that is, turn things into object?
JavaScript has a function statement, which is the "standard" way to declare a function, with the syntax:
function name([param1, 2...]) {
statements
}
And there is a function operator, which looks the same as the function statement except that the name is optional and it is used not as a statement on its own but where an expression is expected as in the following two examples:
// declare variable name that references a function created by expression
var name = function([param1, 2...]) { statements };
// call someOtherFunction that expects a function as a parameter
someOtherFunction(function() { });
(There are plenty of other ways to use function expressions.)
If you try to have an anonymous function on a line by itself without wrapping it in parentheses it will taken to be a function statement and thus be a syntax error because there's no name. Wrapping it in parentheses means it'll be treated as an expression inside the parens and not as a statement so then name is optional. If you assign the result of the function expression to a variable or use it in some other way (like in my examples above) then you don't need the parentheses.
So getting (at last) to the syntax mentioned in the question: once you have the parens and your function is treated as an expression you can use either of the two syntaxes you posted to invoke it. The first, invoke "outside" the parens means the first set of parens will evaluate as having the value of the expression inside, which happens to be a function that you can then invoke. The second, invoke "inside" means function expression will be invoked and then the surrounding parens will evaluate to whatever the function returns.
Either way, the return value of the function is thrown away because you don't assign it to anything.
(Final note: a function expression can have a name so that the function can call itself recursively.)
When you have a regular annon function like:
function() { alert('testing'); }
it's a function expression. Any other vairiation is called a function declaration, like the following:
function a() { alert('testing'); }
!function() { alert('testing'); }
var a = function { alert('testing'); }
(function() { alert('testing'); })
Now a function expression can't be invoked as it's not returning a value, but a declaration can. So all you need to do is somehow switch it to a declaration to immediately invoke, which is what the parens do, whether they wrap the invoking parens or not. This is because once the js parser sees a open parens it makes it into a declaration.
Disclaimer: I may have mixed up the terminology of declaration and expression

Categories