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

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.

Related

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.

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

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

Does parenthetical notation for self-invoked functions serve a purpose in Javascript? [duplicate]

This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 8 years ago.
I get confused when I see examples of self invoked anonymous functions in Javascript such as this:
(function () { return val;}) ();
Is there a difference between this syntax and the following:
function() { return val;} ();
If someone can give me a concrete difference, it would help put to rest a question that's been bugging me for ages...
Javascript doesn't have a block scope, so this is a way to create a temporary local scope that doesn't pollute the global namespace. The parentheses serve two purposes:
Some implementations of javascript flip out if they're missing.
It signals to readers that something different from a normal function declaration is going on. So as a convention, it signals that this function is being used as a scope.
see here:
http://peter.michaux.ca/articles/an-important-pair-of-parens
In Safari 4, the following code (without the parentheses) results in "SyntaxError: Parse error":
function() { alert("Test"); }();
...but the following code works as expected:
(function() { alert("Test"); })();
Update: I also tried the code in Firefox 3 (via Firebug), and it behaved just like Safari.
The reason
function() { return val;} ();
doesn't work is because it's a function statement, not an expression. It's a pretty minor distinction, but basically, if the statement starts with function, it's just like a C function declaration, and you can't call the function, because there is no expression value.
Adding the parentheses makes the function definition part of an expression, so it has a value and can be called.
Assigning the return value of the function also eliminates the need for parentheses, because the function definition is not the whole statement. For example, these work:
var value = function() { alert("works"); return 0; }();
(function() { alert("works"); })();
but this doesn't:
function() { alert("doesn't work"); }();
I always include the parentheses, even when they aren't necessary because it makes it easier to see that I'm calling the function, instead of assigning it to a variable.
As far as I know, the only difference is that the latter sometimes doesn't work in certain flavors of ECMAScript (namely ActionScript, but there could be others).

Categories

Resources