Why add () at the end of an immediately-invoked function expression? - javascript

So I decided to "re-learn" JavaScript since I forgot quite a bit. I stumbled across the "immediately-invoked function expression".
I understood everything except the () at the end.
Example:
!(function(){
console.log("Works");
})() // <----
I noticed that without it, it didn't run. But with it, it worked.
Why does the () matter?
The other, similar questions I found did not have the same exact question, I also searched on the web, still nothing.

The way you execute any function is by putting an argument list enclosed in () after an expression that evaluates to the function.
With normal named functions, the expression is just the name of the function. An IIFE doesn't need a name, because it's just being used this once, so it's just an anonymous function expression.
But you still execute it the same way, by putting an argument list after the expression. Usually an IIFE doesn't need any actual arguments, so the argument list is empty.
(function() {
console.log("Works!");
})();
is essentially the same as
function tempName() {
console.log("Works!");
}
tempName();
except that it doesn't create the name tempName.
And if you left out the () at the end, it would be like writing just
tempName;
which is just a reference to the function, it doesn't invoke it.

Related

Immediately Invoked Function Expression in 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/

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(){
}()

Is there any difference in this JavaScript code? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 6 years ago.
I have seen various code which is implemented in following two way. I always use the second one (2.). I wanted to know two thing here.
Is there any difference between these two codes?
Which one is the best practice (and why) if any?
1.
(function () {
//some code here, angular code
})();
2.
(function () {
//some code here, angular code
});
Please also suggest me some good blog or book in this regards as I wants to learn in more detail. Thank you all advance..
Yes, you are not executing the second one.
In the first example, you are declaring an anonymous function, which gets run afterwards with no parameters.
In the second example, you are just declaring it, but not running it.
() is what makes it run, in this case by passing it no parameters.
This one executes the anonymous function:
(function () {
//some code here, angular code
})();
This one doesn't execute it:
(function () {
//some code here, angular code
});
For example, if you have a parameter, you can pass it like so:
(function (c) {
// c.log() is same as console.log
c.log("hello");
})(console);
Note: I've added the parameter example because it's less obvious without any parameter.
Edit:
As #Osman has just pointed in the comments, the first one is known as IIFE.
This pattern is so common, a few years ago the community agreed on a
term for it: IIFE, which stands for Immediately Invoked Function
Expression.
The second is declaration, the first is declaration and execution.
Difference:
The first one executes the anonymous function expression:
(function () {
//some code here, angular code
})();
The second one doesn't execute it:
(function () {
//some code here, angular code
});
anonymous function is a function that doesn't have a name.
Background:
Basically, first we are wrapping the anonymous function declaration with first brackets, like: (), to make it a function expression:
// this is a function declaration:
function () {
//some code here
}
// this is a function expression
(function () {
//some code here
});
By itself it does nothing, as we are neither executing it, nor declaring it within the current scope. In other words, it's useless. Learn more about the difference between function declaration & function expression.
Now, we can use the function expression as a parameter to some other function, like jQuery does:
// now jQuery is taking the function expression as parameter
$(function () {
//some code here
});
Or, we can execute the function itself by using () at the end (This is how we invoke any function actually - in this case without any parameter):
// Now the function expression gets executed.
(function () {
//some code here, angular code
})();
This is also known as Immediately-Invoked Function Expression or IIFE.
The above examples don't have any parameter. However, if you have a parameter, you can pass it like so while executing:
(function (c) {
// Here c.log() is same as console.log()
c.log("hello");
})(console);
Note: I've added the parameter example because it may be less obvious without any parameter.
Best Practice:
Since functionally they are different, the question of best practice doesn't appear. Usually we use IIFE in cases where we want to execute something in a scope different from the current scope & we don't want to leave any footprint of function declaration, variable declaration etc. within the current scope.
Further Reading:
More discussion about this can be found in the following links:
What is the (function() { } )() construct in JavaScript?
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
What is the purpose of a self executing function in javascript?
You Don't Know JS: Scope & Closures.
The first one is an IIFE (Immediately-invoked function expression ) as others said, for more info on IIFE check this repo by Kyle Simpson (author of You don't know JS)

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 () {
...
} ()

Is there any reason to wrap anonymous JavaScript functions in braces?

var a = function () {
return 'test';
}();
console.log(a);
Answer in First Case : test
var a = (function () {
return 'test';
})();
console.log(a);
Answer in Second Case : test
I am using the the first approach to create self-executing functions. However, I have seen the second approach as well. Is there any difference in the two approaches ? The result is obviously the same.
The first syntax is only valid if you assign the result of the function execution to a variable, If you just want to execute the function, this form would be a syntax error:
function(){
return 'test';
}();
The other form is still valid, though:
(function(){
return 'test';
})();
Therefore the second version is more flexible and can be used more consistently.
(The first form is not valid syntax to avoid ambiguities in the Javascript grammar.)
Yes, the first one sets the variable a as an anonymous variable, while the second one sets the variable a to the result of the function.
Edit: I read the first code wrong. The answer is no.
It is good practice (but not required) to wrap IIFEs (Immediately Invoked Function Expressions) in parenthesis for readability. If your function is long and the reader cannot see the end, the opening parenthesis calls the readers attention to the fact that there is something special about this function expression and forces them to look at the bottom to find out what it is.

Categories