Immediate function invocation syntax - javascript

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

Related

Why can I not .bind(this) when a function is directly declared

Given the following:
function x() {
this.abc = 1;
function f1() {
alert(this.abc);
}.bind(this)
var f2 = function b() {
alert(this.abc);
}.bind(this);
}
What I would like is for the "this" of the outer function to be available inside the f1 and f2 functions.
Why is it that VS2013 tells me there's a syntax error with the bind(this) on function f1() ?
There's a difference between a function declaration statement and a function instantiation expression. Both involve the keyword function, but a declaration statement cannot immediately be used as a reference to a function. A function instantiation expression is part of the expression grammar, so it can be used freely in that context as a reference to a function because that's what it evaluates to.
You can of course do this:
(function a() {
}).bind(this);
though without using the return value from .bind() it's not very useful.
If the first token in a statement is function, then you've got a function declaration statement. If the first token is not function, then you've either got another sort of keyword-introduced statement (for, return, var, try, whatever), or else you've got an expression statement. In that expression (or in any expression in another context), your function instantiations are part of the expression grammar and the value can be used as a reference to a function.
Here's another way to think about the problem. Let's pretend that there is only one way to instantiate a function in JavaScript, and that's the function expression. That is, let's pretend that any use of the function keyword means to instantiate a function and return a reference to that function as it's value.
Now, thinking generally about expressions and the things that participate in expressions, the point is to compute some sort of value. When you need the value 5 as part of an expression, you put 5 in its place and that's that. By itself, 5 is a valid expression, so this is not a syntax error:
5;
What does that do, however? It does nothing. Similarly, in our make-believe JavaScript without function declaration statements,
function foo(a, b) {
return a + b;
};
would also do nothing at all. What would happen is simply that the function would be instantiated but thrown away because the value — the reference to the instantiated function — is not saved as the value of a variable or passed to some function or anything else. In this make-believe JavaScript, you'd use
var foo = function(a, b) {
return a + b;
};
all the time.
The language design does have function declaration statements, however. As a simplifying approach, the language just recognizes a statement whose first token is the keyword function as a completely different sort of statement than an expression statement that happens to contain a function instantiation. There are other ways in which the problem could have been addressed (such as the use of a different keyword), but I suspect that there'd still be confusion.
Note that there are JavaScript programmers who strongly prefer using var declarations for functions. It's a matter of style really.

Javascript/jQuery function arguments

Newbie jQuery / Javascript question here
I see functions written in the following fashion:
some_function = function(event) {
}
My question is: What is meant by that event argument? Is it optional? What if I want to have two additional parameters, X and Y, what would the signature look like? When I call the function now, I can just call it like some_function(); and it works fine (which leads me to believe that it's optional). However, how will that change when I have two additional arguments like X and Y? Can I just call it like some_function(myX, myY) ?
Thanks!
There are two ways to instantiate a function in JavaScript. They both look the same, but their meanings aren't quite the same.
What you've posted is a function instantiation as part of an expression in the language. In that form, the syntax is
function name ( p1, p2, ... ) { body }
The "name" and the parameters are optional; the keyword function and the parentheses are required. (There are some obscure issues with using a name in this case, in some browsers; it's getting to be less of a problem.)
The effect of that is to create a new function object. The reference to the object participates in the expression just like any other value (well, like any other reference to an object). Because it's a function, the reference can also be used to call the function and cause its code ("body") to execute, just like you'd expect. (It wouldn't be much of a function if you couldn't!)
The other way a function can be instantiated is with a function declaration statement, which looks, surprisingly, exactly the same (except that "name" is required). The difference involves where exactly in your code the keyword function appears:
If the keyword function is the first thing in a new statement, then you've got a function declaration and the "name" is required. The statement is not an expression statement in this case, and the only thing the statement does is instantiate the function and bind a reference to the function to "name" more or less as if "name" were a local variable (or global if in the global scope).
If the keyword function appears anywhere else in an expression (either an expression statement, or an expression buried inside some other context, like the top of a for or while loop statement), then it's a function instantiation expression.
Now, regardless of how a function is "born", once you've got a reference to the function you can call it and pass as many parameters as you like.
I don't know personally how the trend started, or whether it's even something that should be considered a trend, but it's fairly common to see local functions instantiated with code like this (and like what you posted):
var some_function = function( arg1, arg2 ) {
/* some code */
};
That's an example of a function instantiation in an expression. The net effect is that the symbol "some_function" is bound to the newly-created function. There are slight nitpicky differences, however, between the way that name is bound to the function from the (almost) equivalent function declaration:
function some_function( arg1, arg2 ) {
/* some code */
};
One simple reason that the second way (function declaration statement) is a little better is that the name of the function will show up in stack traces. Of course, one could achieve that with the redundant-looking:
var some_function = function some_function( arg1, arg2 ) {
/* some function */
};
I don't really know why you'd want to do that, but it'd work, except in some naughty environments.
That code snippet is a little vague, however I can answer, in general, your questions.
The event argument, in the code you provided, is just what that function will use to reference the first parameter that is passed to the function from whatever-other code calls it. For example, if you had code that called your some_function function, and passed it a string "hello world!", the call would look something like:
obj.some_function("hello world!")
Inside of the some_function function, the variable event would contain "hello world!". Also, you could change your some_function signature to be: some_function(blah) and it would be all the same, you would just use blah to reference the parameter instead of event. The variable name you choose for parameters is entirely up to you, though you want to make sure you don't use language-reserved names (like in, for, continue, break, etc)
Technically all parameters are optional for a JavaScript function, unless the internal code of the function enforces the parameters (i.e. it may return or throw an error if a parameter is missing.
#Pointy answered the other point I was going to make...that the code you provided is defining that function as an expression. I use that syntax when I'm creating a function that is an attribute of an object (which is why my above code has obj. at the beginning.

Grammar of Self Invoking Anonymous Functions

From what I have read from other topics about the issuse SIAFs or Self Invoking Anonymous Functions are simply there to serve as a container, and it limits the scope of variables (from what I have learnt). Now, the question is, why can I do this:
$("ul>li").click((function(){
}));
But not add another SIAF after it? Like so:
$("ul>li").click((function(){
}));
(function(){
});
It is weird to me, as this, just the SIAF on its own gives me no errors in the IDE:
$("ul>li").click((function(){
}));
(function(){
});
This:
(function() { .. });
is a no-op expression, and in particular it does not involve a function call. A function object is instantiated but it's not used in any way.
This:
(function() { ... })();
does do something, because the trailing () causes the function to be invoked. (It doesn't invoke itself.)
In JavaScript, a reference to a function is just a value, and a function is just an object (well, a special object). When a reference to a function is followed by a parenthesized list of values, then that's a function call. It doesn't matter where the reference to the function comes from. (Where it comes from can affect the semantics of the function call, but not the basic fact of the function call itself.)
edit — the terminology "self-invoking function expression" has gained some currency. I won't wade into a dispute, but in my opinion it's less accurate than the alternative "immediately-invoked function expression" because really a function can't invoke itself externally. It can include a call to itself, but that's a different thing entirely. However I understand the spirit of the term and I think it's harmless.

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.

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

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

Categories

Resources