JavaScript anonymous function immediate invocation/execution (expression vs. declaration) [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
What is the difference between a function expression vs declaration in JavaScript?
Explain JavaScript's encapsulated anonymous function syntax
Why this:
(function () {
//code
}());
and this:
var f = function () {
//code
}();
works, while this:
function () {
//code
}();
does not? It looks exactly the same - anonymous function defined, and immediately called. Can someone make a quotation from the JavaScript/ECMAScript standard which explains that?
UPDATE: Thanks for the answers everyone!
So it's about function expression vs. function declaration. See this Stack Overflow answer, ECMAScript standard section 13, and this great article: Named function expressions demystified.
To recap answers:
The first snippet is interpreted as an expression because the grouping operator, (), is applied - see ECMAScript standard section 11.1.6.
In the second snippet, the function is interpreted as an expression because it's on the right-hand part of assignment operator, =.
The third snippet doesn't have anything which allows the interpreter to read the function as an expression, so it's considered a declaration, which is invalid without an identifier (Gecko lets it pass however, but it chokes on following () grouping operator (as it thinks) applied to nothing).

The first two cases show function expressions, and can appear anywhere an expression like (1+1 or x*f(4)) would appear. Just like how 1+1, evaluates to 2, these expressions evaluate to a corresponding function.
The third case is a function declation statement, and can appear anywhere you can have other statements (like an if or while statement).
There is not much point in trying to declare an anonymous function via a Funcion declaration statements, since otherwise noone would get a reference to the function afterwards.
The reason you need the opening ( or the var x = like in the first two cases is that they force next bit to be parsed in an expression context. (just think how you cant do var x = if ..., for example). If you just put the function as the first thing it will be parsed as the declaration statement you don't want.

The first two are something called a function expression, meaning it's inline and interpreted as the JS code runs.
The 3rd is a function declaration and is interpreted when the code is compiled. Since it's interpreted at compilation, you can't immediately run it since none of the other code around it has been run yet.
To show an example:
// foo == undefined
// bar == function
function bar(){ .. }
var foo = function(){ ... }
// foo == function
// bar == function
Put simply, any time you have the word function without anything preceding it, it's a declaration. Any time something precedes it, it's an expression.

Here's a simple way to think of it: If function is the first keyword on the line, the parser will interpret the rest of the line as a function declaration. In other words, it will think you're trying to write something like this, as if you've forgotten to name your function:
function foo(){
// code
}
The way to get around this is either to wrap the entire function inside some parens or make it part of a variable assignment. In either case, you're putting function further back on the line and allowing the parser to recognize you're not writing a function declaration.
It kind of seems trivial to me to allow function to appear at the start of a line and still distinguish between function expressions and function declarations, but I guess it wasn't so trivial back when JavaScript was first being designed.

Anonymous functions are explained well in Stack Overflow
question Why do you need to invoke an anonymous function on the same line?.

Related

Are named callbacks function expressions?

Given the following example:
setTimeout(function name(){console.log(1)}, 1000) (callback)
Is name() (the callback) considered a function declaration or a named function expression?
I know that function declarations are hoisted and function expressions are not, but because it is within the context of an argument, how would you determine whether you can hoist it or not?
I don't believe it to be a duplicate of what is the difference between function declarations and function expressions.
I'm asking a specific usecase of whether or not named callback functions are function declarations or function expressions. I do not believe this usecase to be covered within the answers provided within that question.
Generally speaking, if a function definition is in an expression position, then it's a function expression.
When is something an "expression position"? When you cannot put a statement there.
Arguments are expressions (you would not be able to pass an if statement as an argument) therefore function name() {...} is an expression in your example.
And because it is a function expression you could omit the name.
Now you might be wondering about the following: Assuming you know that 5 + 5 is an expression and that you can put 5 + 5 in a line just like so
5 + 5;
it seems we can put expression anywhere we want. So how does JavaScript decide, given
function name() {
//...
}
whether it is a function declaration or a function expression?
To answer this question we have to look at how the code is structured in general. At the top level, all you have is a list of statements:
<statement1>
<statement2>
<statement3>
...
There are various types of statements, an if statement is one example. There is also the concept of an ExpressionStatement. As the name implies, it's a statement that consists of a single expression. This is the rule that allows you to put 5 + 5; in that list of statements.
But this parsing rule is restricted. It cannot start with the keyword function (among others). Therefore, when JavaScript encounters the above function definition, it won't be parsed as a function expression, because it cannot parse it as an ExpressionStatement. The only choice left is to parse it as a function declaration.
If you are curious about the structure of a JavaScript program you can use https://astexplorer.net (full disclosure: I built this site) to see how popular JavaScript parsers pare the program.
For example,
setTimeout(function name(){console.log(1)}, 1000)
is parsed to
by acorn.
(you should really look at the live version though, because hovering over the AST highlights the corresponding source text, which makes things easier to understand)
Yes, it is an expression. And the function is callable by its name from within itself.
Try this out:
setTimeout(function name(){
console.log(1);
console.log(name);
}, 1000)
Invoke it with a stop-condition though, otherwise you'll run out of stack. Recursions bite...

Purpose of the outer extra parenthese on JavaScript closure function [duplicate]

This question already has answers here:
JavaScript - self-executing anonymous functions and callback
(2 answers)
Closed 9 years ago.
What is the purpose of the outer extra parentheses on the below JavaScript closure function? I have been told in other posts that they are not strictly necessary, but they're a convention to make it clear that the result of the function is being passed, not the function itself. The below quote from http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
, however, conflicts. Which is correct?
Notice the () around the anonymous function. This is required by the
language, since statements that begin with the token function are
always considered to be function declarations. Including () creates a
function expression instead.
(function () {
// ... all vars and functions are in this scope only
// still maintains access to all globals
}());
I think that different engines have different ways of interpreting
function(){...}();
so the most popular and accepted way to make it clear, to all engines, is to group the code in parentheses.
(function(){...}());
At the same time, what you quoted makes a very interesting point. A function expression might go:
var f = function() {...}
Whereas a function declaration looks like:
function f() {...}
You see how it's easy/convenient for the parser to tell the difference by looking at the first token?
IF TOKEN1 EQ "function": FXN DECLARATION
ELSE: FXN EXPRESSION
But it wouldn't make sense for your (immediately-invoked) function to be a function declaration (it's not going to be re-used, you don't want to have it hoisted, or in the namespace, etc.) so adding some innocuous parentheses is a good way of indicating that it's a function expression.
First of all, I must clear up:
(function () {
}());
is equivalent for
(function () {
})();
and also for (Backbone.js uses it)
(function(){
}).call(this);
Second, if you're going to use it that way, then it's not an anonymous/closure function. its Immediately-Invoked Function expression
it would act as a closure (because it won't be immediately-invoked) if you assign its returned context to a variable. This kinda useful if you need a static class (when properties and methods could be accessed without instantiation). For example:
var stuff = (function(){
// AGAIN: its not an IIFE in this case
function foo() // <- public method
{
alert('Jeeez');
}
return {
foo : foo,
}
})();
stuff.foo(); //Alerts Jeeez
What is the purpose of the outer extra parentheses on the below
JavaScript closure function?
The purpose isn't usual and quite strange - its all about function arguments.
For example,
(function(window, document){ // <- you see this? 2 "arguments"
alert(arguments.length); // 0!
})();
but if we pass them to that outer parentheses
(function(/* So its not for arguments */ ){
alert(arguments.length); // 2
})(window, document); // <- Instead we pass arguments here
The extra surrounding parentheses disambiguate a function expression from a regular function declaration.
Though the extra parentheses are standard practice, the same thing can be achieved by doing this instead:
void function() {
// do stuff
}();
Or, even:
+function() {
// do stuff
}();
Though, out of these two alternatives, I prefer the void notation because in most cases we don't really care about the return value of an immediate invocation.
Other places where the parentheses aren't required is when an expression is expected:
setTimeout(function() {
return function() {
alert('hello');
}
}(), 1000);
They are necessary because the parser goes in the function declaration mode when it sees
function
in a statement context.
After function token, it is expecting a name for the function because a function declaration must include a name for the function. But instead of a name it sees ( instead, so it's a syntax error.
I think, it could backtrack and unambiguously just treat it as a function expression but it doesn't.
var module = XXX
In the above, XXX is in expression context, if a function appears there, it is treated as a start of a function expression. Function expressions don't have to have
a name for the function, so it's not a syntax error to have ( appear right after function.
So you can write:
var module = function(){}();
But not
function(){}()
You can use many tricks to make the above an expression:
(XXX)
!XXX
~XXX
+XXX
//This doesn't work however:
{YYY} //the braces are delimiting a block, and inside block you start in
//a statement context
XXX is in expression context because it's enclosed by parenthesis or is following a unary operator, therefore any function substituted for XXX is a function expression.

javascript self-executing functions - different syntax [duplicate]

This question already has answers here:
Are "(function ( ) { } ) ( )" and "(function ( ) { } ( ) )" functionally equal in JavaScript? [duplicate]
(3 answers)
Closed 8 years ago.
I've seen 2 versions of self executing javascript functions:
(function() { ... })()
and
(function() { ... }())
note the different placement of the function execution "()"
Is there a difference between these two?
There are many ways to get the effect of what you're doing, and strictly speaking this topic has only tangential relation to the subject of closures.
The problem is this: in JavaScript, the function keyword serves two different purposes:
It introduces a function declaration statement, which is kind-of like a var statement (variable declaration) but for a function;
It introduces a function literal expression in the context of a larger expression.
Now the problem is that when the parser sees function at the beginning of a statement, it assumes you mean to declare a function; that is, case 1 above. When you declare a function, you cannot call it in the same statement; the function declaration statement just declares the function.
Thus, if what you want is a statement that consists only of the creation of a function and its immediate invocation, you have to put the parser in the mood to parse an expression. Putting the whole thing in parentheses is just one way of doing that.
Any "trick" that convinces the parser that what it's seeing is an expression statement will do:
var dummy = function() { ... whatever ... } ();
!function() { ... whatever ... } ();
0 + function() { ... whatever ... } ();
All of those, and countless other examples, set things up such that when the parser sees the function keyword, it does so in the middle of an expression.
If Mr. Eich had picked a different keyword for the instantiation of a function object mid-expression (like lambda for example), there'd be no problem, because you could then just say
lambda () { ... whatever ... } ();
He didn't, however.
The parenthesis ensure you have an expression (which cannot starts by the function keyword), so that it may be executed.
From ECMAscript Language Specification :
Also, an
ExpressionStatement cannot start with the function keyword because
that might make it ambiguous with a FunctionDeclaration.
This works too :
(((((function() {...}))())));​
The correct term for either of these is an immediately executing function.
Although both of these work in the same way, Douglas Crockford recommends the latter for reasons of readability.
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 if you want to follow that advice, you should prefer to use:
(function() { ... }())
Former is better because it treats Function as a `first-class citizen'. It use parenthesis to wrap the function and invoke it.
Em..as to latter, it also avoid syntax ambiguous.
But I recommend the former.

Why are parenthesis used to wrap a javascript function call? [duplicate]

This question already has answers here:
Are "(function ( ) { } ) ( )" and "(function ( ) { } ( ) )" functionally equal in JavaScript? [duplicate]
(3 answers)
Closed 9 years ago.
What is the difference between these two javascript function calls?
(function(){alert("foo")})()
versus this:
(function(){alert("foo")}())
This is done for readability.
There isn't a real functional difference between the two examples you've given, but both of them are very close to a simple function declaration, which is different. The parenthesis are added for readability, in order to distinguish them.
Here is what each of your snippets do:
In the first of your two snippets, the first parenthesis will be evaluated as the value of the enclosed function. Then this value will be called as a function. So ultimately the function will be executed, which is probably what you care about.
In your second snippet, the outer parenthesis will be evaluated as containing a function which is declared inline and immediately executed. Again, the function will be executed, which is still probably what you care about.
Both of these will execute the same function, so there won't be any significant difference.
The difference between a snippet like yours and a simple function declaration:
The functions you've given are also identical to the following. I've just added a function name and assigned the return value for syntactical accuracy, which you can ignore for now.
// javascript...
var val =
function myFooFunc () {
alert("foo");
}();
However, this would be easily mistaken for a simple function declaration, which is different:
// javascript...
function myFooFunc () {
alert("foo");
}
Notice that the only real difference here is that this last function declaration is not executed immediately. The others are. So that is a very different behavior (the simple declaration may be executed later if it is called by name, or it may not ever execute at all). It's often hard to see that difference in the syntax right away, however, especially if the function body grows to be very long and requires scrolling on the screen.
Why are functions executed immediately?
When a function is immediately executed after it is declared, the value is often being returned to something (it may be part of an assignment statement). Sometimes the function is being executed right away because it contains inner functions and is being used to provide functional scope to the inclosed statements.
Essentially, people wrap parenthesis around the "executed immediately" form (both of your snippets, and the first one of my two) in order to give a visual cue to other developers that the function is being called immediately. It's just easier to read, since you might not catch the parenthesis until you got to the end of the function (or notice them at all).
They both have similar behaviors.
The parentheses encapsulating the function declaration tell the JavaScript engine to execute the code immediately after it's parsed. In the first example, you're creating a function object then invoking it with the parentheses that follow. In the second example, you are telling the JavaScript engine to create the function object and invoke it immediately.
Example:
// creates a function object
var f1 = (function() { alert('foo'); });
// creates a function object and executes it immediately
var f2 = (function() { alert('foo'); }());
The difference is that f1 gives you a function object. f2 creates and invokes an anonymous function.

Immediate function invocation syntax

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

Categories

Resources