Different ways to execute IIFE? - javascript

Is there any difference between
(function (){alert('')} ())
vs
(function (){alert('')}) ()
Both works but when should I use each ?

The wrapping parentheses are only there to force the parser to parse the construct as a function expression, rather than a function declaration. This is necessary because it's illegal to invoke a function declaration, but legal to invoke a function expression.
To that end, it doesn't matter where the invoking parentheses go. It also doesn't matter how you force the function to be parsed as an expression. The following would work just as well:
!function () {
alert('')
}();
~function () {
alert('')
}();
// Any unary operator will work
If you decide to use the wrapping parentheses (grouping operator), then just bear in mind that JSLint will tell you to move the invoking parentheses inside. This is simply a stylistic choice and you can ignore it if you want.

They both do the same thing.
JSLint recommends you use the first, with the executing parentheses inside the grouping parentheses, presumably so everything's neatly grouped together.
For what it's worth, I personally think your second example is much clearer as when scanning the code you can see the execution as standing out from the function expression.
Though not a duplicate, this question covers similar ground so might be worth a look.

Related

Please explain two syntaxes for IIFE

Is there any difference between: (function () {})(), and (function () {}())?
I've seen both constructs referenced, and would like to know if they represent two equivalent ways of constructing the exact same expression, or are they two different expressions/constructs altogether? If different, how are they different?
These expressions are equivalent.
A closure is created, then called. The value of the expression is the closure's return value.
The simplest form would be function () {}(), however at the top level, where an IIFE would be used, that is a SyntaxError. Therefore either the creation of the closure, or the whole expression is parenthesized.
However it would work in an expression context, for example
let a = function () {}()
Update: A third form you'll sometimes see, for example in minified JS is !function () {}(), of course the return value is different in this case.

Using eval to execute functions

There is something I don't understand about how eval works.
Suppose I have a function foo:
function foo() {
console.log("test");
}
And then I write
eval("foo()");
or
eval("foo" + "();");
The function foo is executed and I have "test" printed out.
However, if I write:
eval("function foo() { console.log(\"foo\"); }();");
or
eval("function foo() { console.log(\"foo\"); }" + "();");
I get "SyntaxError: Unexpected token )".
Why is that? I saw that when I pass the function name it is evaluated into the function's code, so I though it's supposed to be the same as "eval("foo" + "();");"
I'm using Chrome 27 if it makes any difference.
Because no answer is specific about why the last snippet fails, and nobody seems to be warning you for the dangers of eval:
eval, according to MDN:
A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.
Your string, "function foo(){console.log('foo');}()" actually consists of 2 statements, that make no sense to the JS engine. Well, the second one doesn't:
function foo(){console.log('foo');}//function declaration, fine
;//<-- js adds implied statement terminator
()//no invocation, because no function reference, group nothing ==> does not compute, raise error
That's why you have to turn your function declaration statement into an expression, by adding an operator. Typically, this is the grouping operator: ()
(function foo(){ console.log('foo')});
The function declaration is now an expression, everything (the grouping () included) can be seen as a statement, unless the code that follows belongs to the code above. In this case, the invoking parentheses clearly do, so the JS engine sorts it out for you.
For clarity, some say the preferred notation is:
(function f(){}());//<-- invoking parentheses inside group
Which makes sense, because the invocation is part of the statement, after all.
If you don't like all these parentheses, any operator will do:
~function(){}();//bitwise not
+function(){}();//coerce to number
Are all equally valid. Note that they will change the possible return values of the function expression.
(function(){}());//resolves to undefined
+function(){}();//resolves to NaN, because undefined is NotANumber
How your eval could look, then, is any of the following:
eval("(function (){console.log('foo');}());");
eval("~function (){console.log('foo');}();");
eval("!function (){console.log('foo');}();");
And so on, and so forth...
Lastly, eval evaluates code in the global scope, so any code eval-ed containing functions can, and likely will, polute the global namespace. Mallicious code will also have access to everything, so be weary of XSS attacks and all other JS based techniques.
Bottom line, eval is evil, especially since all browsers now support JSON.parse natively, and for those that don't, there still is a tried and tested JSON2.js file out there.
Using eval in strict mode does make things slightly safer, but doesn't prevent XSS attacks at all, the code can still manipulate the DOM, for example, and reassign exposed DOM references or objects.
Google "why eval is evil" if you want to find out more.
Also check the ECMAScript specs
function x() {} is a statement, whereas everything else you're doing is an expression, and you can only evaluate expressions.
The other answers explain how you can turn this statement into an expression. Thought I'd let you know why you actually get an error, though. :)
eval("(function() { console.log(\"foo\"); })()");
This is called a self-executing anonymous function.
you would need to call
eval("function foo() { console.log(\"foo\"); };" + " foo();");
in order for this to work;
Put brackets around your function
eval("(function foo() { console.log(\"foo\"); })()");
It is like calling
(function foo() { console.log("foo"); })()
The main thing you should understand about eval is that it is evil. Don't use it... ever. There is always a way to achieve the same thing by dynamically creating a script document or by using a closure.
Read Douglas Crockford: JavaScript the good parts.

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

JS: What's the difference between a ! closure and () closure? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does the exclamation mark do before the function?
So I was going back and looking over some of my own code as well as some other javascript code and I realized that a while back when I started writing javascript libraries I was using closures that looked something like this:
(function( window, document, undefined ) {
// code
})( window, document );
But then I saw some bootstrap code and I changed to this syntax:
! function (window, document, undefined) {
// code
}(window, document);
Now, if I'm not wrong (and please correct me if I am), placing the '!' in front of my anonymous function just causes it to be treated as '()' then returns (into nowhere?) a boolean value of whether the value returned by the function was not undefined, null, or empty.
What I'm wondering is, is there really a difference between using the '!()' syntax over '()()'? Are there certain browsers that will complain?
Any thoughts are appreciated, thanks! XD
What you're asking about is self-calling functions, otherwise known as IIFE (immediately invoked function expression). Which is a different thing from a closure. Although it does create a closure (indeed, all functions in javascript create closures, not just IIFE).
It's understandable that you may confuse the two issues though, since IIFE are usually introduced in the context of explaining closures. But be aware that they are different things. Closures are private, shared "global-like" variables. IIFE are functions that gets called immediately upon their definitions.
Now, how does IIFE work? The clue is in the name. It's the "FE" IIFE - function expression.
In javascript, as you know, there are two ways of creating functions - using function declarations:
function foo () {}
and using function expressions:
foo = function () {}
A function expression is simply a function declared in the context* of an expression. What are expressions in javascript? Simply any statement that evaluates something.
Traditionally, people recognize expressions as:
anything on the right side of the = sign
a = /* expression */
anything in braces
(/* expression */)
So traditionally those are the two "standard" ways for declaring function expressions:
foo = function(){}
and
(function(){})
And the second syntax makes it easy to then execute the function object returned by the expression. But, really, an expression is anywhere js does math (or logic, which is math anyway). So adding an operator to a function declaration also turns it into an expression. The following works because they are unary operators (meaning, they are legal without anything on the left hand side):
!function(){}()
+function(){}()
-function(){}() // I especially like this one because it
// looks like a command line switch
typeof function(){}()
But you can also use binary operators if you use some throw-away value or variable with it. The following also work:
x=function(){}()
0==function(){}()
1*function(){}()
2/function(){}()
Heck, you can even abuse the ternary operator:
0?0:function(){}() // valid and works!
There's nothing magical about it. It's not a specific syntax baked into javascript. Just like (function(){}()) is not a specific syntax for IIFE. It's just that when declared in an expression, functions return themselves as objects which can be called immediately.
But I'd advise against using any of the non-standard forms above though. For the same reason you asked this question - most javascript programmers are not used to seeing them and it can cause confusion. I myself didn't realize that you can do this until you asked the question. Still, it's a useful thing to know for when you need to write things like minifiers, code generators etc.
* I'm using "context" in it's traditional definition here not the javascript specific meaning of "context" as defined in the spec.
Nothing, they are just two different ways of achieving the same thing. The () is slightly more readable though.

How should I declare my self-calling function?

I've seen self-calling functions in Javascript written like this:
(function () {
// foo!
})();
But I've also seen them written like this:
(function () {
// bar!
}());
Syntactically, they do exactly the same thing. My personal habit is the first format, actually, but is there any difference between the two that I should be aware of? Like browser kinks or whatever?
One very trivial thing, for example, is if the second format should work reliably, then it would mean that something like this should be possible as well:
function () {
// shut the front door! saved two characters right there!
}();
It hurts readability a good deal though.
First:
There is, like you assumed, absolutely no difference between the first two version of your self-invoking anonymous function. No browser klinks, quirks, just comes down to personal preference (Douglas Crockford calls the latter form "dog balls" by the way).
Second:
function() {
}()
will not work by design, since that statement creates a function statement/declaration. You need a function expression to immediately invoke itself. To create a function expression you can do multiple things. Putting the whole statement into parenthesis is one way, but you could also write
!function() {
}()
or
+function() {
}
All of these operators will make an expression.
The first two are identical, but if I remember correctly, one of them is preferred by jsLint (I think it’s the second).
The third raises a syntax error in most interpreters, but there are other variants:
!function() {
alert('I’m executing myself!');
}();
var noname = function() {
alert(noname); // undefined!
}();
​
You can replace the ! with a + or - ( None of them will make Crockford happy )
This is mostly a convention issue.
(function () {}()); <- one less stack frame before execution (maybe)
(function () {})(); <- executed outside the parenthesis, so one tiny little frame before execution, although I don't like this style, IMO it's visually disconnected.
function () {}(); <- this is just bad practice IMO, it's not immediately obvious that this is an IIFE which is mostly due to convention, but this also has the problem that if you forget a semi-colon before the expression it will, under some conditions silently assign variables the value undefined.
Example:
var x = 0,
y = 1,
z = 3,
function () {
alert("Z is now undefined, instead of throwing a syntax error.");
}();
As mentioned by Andre Meinhold, this is not in expression position.
Pragmatically speaking, JSLint will complain about the first and prefer the second format. Beyond that, it's really personal preference and consistency is key here.
The third format will result in a SyntaxError, so you can't use that. That's because your creating a function declaration, not a function expression. It's the function expression that you're calling when you use the immediate function pattern.
Crockford says to use (function () {...}()).
It's just a stylistic choice, but it's in the community's interest to agree upon a convention and (at the risk of starting a flame-war) why not use Crockford's?
Also, keep in mind that (function () { }()); adds potential confusion. Since in a long function, someone not paying attention might see two closing parentheses and only one being opened.

Categories