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.
Related
I've seen different developers include semicolons after functions in javascript and some haven't. Which is best practice?
function weLikeSemiColons(arg) {
// bunch of code
};
or
function unnecessary(arg) {
// bunch of code
}
Semicolons after function declarations are not necessary.
The grammar of a FunctionDeclaration is described in the specification as this:
function Identifier ( FormalParameterListopt ) { FunctionBody }
There's no semicolon grammatically required, but might wonder why?
Semicolons serve to separate statements from each other, and a FunctionDeclaration is not a statement.
FunctionDeclarations are evaluated before the code enters into execution, hoisting is a common word used to explain this behaviour.
The terms "function declaration" and "function statement" are often wrongly used interchangeably, because there is no function statement described in the ECMAScript Specification, however there are some implementations that include a function statement in their grammar, -notably Mozilla- but again this is non-standard.
However, semicolons are always recommended where you use FunctionExpressions. For example:
var myFn = function () {
//...
};
(function () {
//...
})();
If you omit the semicolon after the first function in the above example, you will get completely undesired results:
var myFn = function () {
alert("Surprise!");
} // <-- No semicolon!
(function () {
//...
})();
The first function will be executed immediately, because the parentheses surrounding the second one will be interpreted as the Arguments of a function call.
Recommended lectures:
Named function expressions demystified (great article)
Explain JavaScript’s encapsulated anonymous function syntax (more on FunctionDeclaration vs FunctionExpression)
I use them after function-as-variable declarations:
var f = function() { ... };
but not after classical-style definitions:
function f() {
...
}
JS Lint is de-facto convention, and it says no semicolon after function body. See the "Semicolon" section.
Just stay consistent! They are not needed, but I personally use them because most minification techniques rely on the semi-colon (for instance, Packer).
Really just depends on your preference. I like to end lines of code with semi colons because I'm used to Java, C++, C#, etc, so I use the same standards for coding in javascript.
I don't typically end function declarations in semi colons though, but that is just my preference.
The browsers will run it either way, but maybe some day they'll come up with some stricter standards governing this.
Example of code I would write:
function handleClickEvent(e)
{
// comment
var something = true; // line of code
if (something) // code block
{
doSomething(); // function call
}
}
It's actually more than an issue of convention or consistency.
I'm fairly certain that not placing semicolons after every statement slows down the internal parser because it has to figure out where the end of the statement is. I wish I had some handy numbers for you to positively confirm that, but maybe you can google it yourself. :)
Also, when you are compressing or minifying code, a lack of semi-colons can lead to a minified version of your script that doesn't do what you wanted because all the white space goes away.
When I minified my scripts I realized that I need to use semicolon for functions which starts with equals mark. if you define a function as var, yes you need to use semicolon.
need semicolon
var x = function(){};
var x = new function(){};
this.x = function(){};
no need semicolon
function x(){}
the semicolon after a function is not necessary
using it or not, does not cause errors in your program.
however, if you plan to minify your code, then using semicolons after functions is a good idea.
say for example you have code like the one below
//file one
var one=1;
var two=2;
function tryOne(){}
function trytwo(){}
and
//file two
var one=1;
var two=2;
function tryOne(){};
function trytwo(){};
when you minify the both, you will get the following as output
Note that comments are just for ilustration
//file one
var one=1;var two=2;function tryOne(){}
function trytwo(){}
and
//file two
var one=1;var two=2;function tryOne(){};function trytwo(){};
Edit:
It doesn't matter with ECMAScript 2021 (ES2021) so please ignore the below statement.
It is a good practice to leave the semicolons ; after the end of function braces. They have been considered a best practice.
One advantage of always using them is if you want to minify your JavaScript.
As minifying the Javascript, helps to reduce the file size a bit.
But as for the best practise and answer above, not recommended to use it after a function tag.
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.
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 this the correct way:
(function() {
// do something here
}());
Or this way:
(function() {
// do something here
})();
It's only a difference in style, both are "correct." I prefer the second and would venture that it's more popular, some prefer the first.
What you can't do is simply
function() {
// ...this example is wrong and won't work
}();
You need the parentheses in order to put the parser in the right mode that you're doing a function expression rather than a function declaration, but it doesn't matter whether the invoking parens at the end are within the main parens or outside them. You can try it with this live copy with the JavaScript engines in your favorite browsers...
Both work, although I use the second method (and see it used more often).
When you surround the function with parentheses, it becomes an expression (i.e. something that evaluates to a value). In other words, for the first example, its saying (evaluate me and execute me), and for the second is saying (evaluate everything in here)(and then execute me). I think the second is more intuitive because it separates what you are executing from the actual execution.
As others pointed out, you need something before "function" to make the parser treat this as an expression, but not necessary a parenthesis. For example, Objective C fans can also use these:
-function() { ... } ()
+function() { ... } ()
example :
function doSomething() { // The function code goes here }
You can click on
http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx
For More information :)
I've seen different developers include semicolons after functions in javascript and some haven't. Which is best practice?
function weLikeSemiColons(arg) {
// bunch of code
};
or
function unnecessary(arg) {
// bunch of code
}
Semicolons after function declarations are not necessary.
The grammar of a FunctionDeclaration is described in the specification as this:
function Identifier ( FormalParameterListopt ) { FunctionBody }
There's no semicolon grammatically required, but might wonder why?
Semicolons serve to separate statements from each other, and a FunctionDeclaration is not a statement.
FunctionDeclarations are evaluated before the code enters into execution, hoisting is a common word used to explain this behaviour.
The terms "function declaration" and "function statement" are often wrongly used interchangeably, because there is no function statement described in the ECMAScript Specification, however there are some implementations that include a function statement in their grammar, -notably Mozilla- but again this is non-standard.
However, semicolons are always recommended where you use FunctionExpressions. For example:
var myFn = function () {
//...
};
(function () {
//...
})();
If you omit the semicolon after the first function in the above example, you will get completely undesired results:
var myFn = function () {
alert("Surprise!");
} // <-- No semicolon!
(function () {
//...
})();
The first function will be executed immediately, because the parentheses surrounding the second one will be interpreted as the Arguments of a function call.
Recommended lectures:
Named function expressions demystified (great article)
Explain JavaScript’s encapsulated anonymous function syntax (more on FunctionDeclaration vs FunctionExpression)
I use them after function-as-variable declarations:
var f = function() { ... };
but not after classical-style definitions:
function f() {
...
}
JS Lint is de-facto convention, and it says no semicolon after function body. See the "Semicolon" section.
Just stay consistent! They are not needed, but I personally use them because most minification techniques rely on the semi-colon (for instance, Packer).
Really just depends on your preference. I like to end lines of code with semi colons because I'm used to Java, C++, C#, etc, so I use the same standards for coding in javascript.
I don't typically end function declarations in semi colons though, but that is just my preference.
The browsers will run it either way, but maybe some day they'll come up with some stricter standards governing this.
Example of code I would write:
function handleClickEvent(e)
{
// comment
var something = true; // line of code
if (something) // code block
{
doSomething(); // function call
}
}
It's actually more than an issue of convention or consistency.
I'm fairly certain that not placing semicolons after every statement slows down the internal parser because it has to figure out where the end of the statement is. I wish I had some handy numbers for you to positively confirm that, but maybe you can google it yourself. :)
Also, when you are compressing or minifying code, a lack of semi-colons can lead to a minified version of your script that doesn't do what you wanted because all the white space goes away.
When I minified my scripts I realized that I need to use semicolon for functions which starts with equals mark. if you define a function as var, yes you need to use semicolon.
need semicolon
var x = function(){};
var x = new function(){};
this.x = function(){};
no need semicolon
function x(){}
the semicolon after a function is not necessary
using it or not, does not cause errors in your program.
however, if you plan to minify your code, then using semicolons after functions is a good idea.
say for example you have code like the one below
//file one
var one=1;
var two=2;
function tryOne(){}
function trytwo(){}
and
//file two
var one=1;
var two=2;
function tryOne(){};
function trytwo(){};
when you minify the both, you will get the following as output
Note that comments are just for ilustration
//file one
var one=1;var two=2;function tryOne(){}
function trytwo(){}
and
//file two
var one=1;var two=2;function tryOne(){};function trytwo(){};
Edit:
It doesn't matter with ECMAScript 2021 (ES2021) so please ignore the below statement.
It is a good practice to leave the semicolons ; after the end of function braces. They have been considered a best practice.
One advantage of always using them is if you want to minify your JavaScript.
As minifying the Javascript, helps to reduce the file size a bit.
But as for the best practise and answer above, not recommended to use it after a function tag.