This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there a difference between (function() {…}()); and (function() {…})();?
I've seen the following syntax used to prevent variables from getting into global scope:
(function ($, undefined)
{
})(jQuery);
More recently I've seen code doing it this way:
(function ($, undefined)
{
} (jQuery));
I find the 1st way makes the most sense to me. I mentally read it as:
I've defined a function and I wish to wrap it into an expression, (the first set of parenthesis). That expression is a function object which I then wish to call using method syntax and the parameter I'm passing to this function object is jQuery.
The 2nd syntax is less clear to me, because it looks like the outer parenthesis are unnecessary.
My javascript knowledge isn't quite good enough yet to feel comfortable w/ the 2nd syntax.
Do these produce identical behavior? Is there any difference at all?
What would happen if you did this?
function ($, undefined)
{
} (jQuery);
If a function keyword occurs at the start of a line it is parsed as a function statement declaration. Funcsion statements require a function name so the 3rd option you present is not allowed (you can test that yourself).
If the function keyword appears elsewhere it is parsed as a function expression and is allowed to be anonymous. There are many ways to do this but the convention for the module pattern you shown is wraping the construct in parenthesis. (Some byte-savers like using a unary operator like + or ~ instead)
If you choose to use the parenthesis puting the last one inside (1st version) or outside (2nd version) is a matter of personal preference. I prefer the 2nd one since the parenthesis wraps the whole pattern instead of just the function.
The reason you're seeing it done the second way is simply a matter of convention. A lot of people run their code through jslint.com (or node-jslint). By default, the lint tool will complain about the first version of the immediate function.
To see this in action, paste the following code into the textarea at jslint.com and run the tool:
/*jslint devel: true, browser: false, sloppy: false, maxerr: 50, indent: 4 */
(function (a) {
'use strict';
alert(a); // Yay!
}("Yay!"));
(function (b) {
'use strict';
alert(b); // Yay!
})("Yay!");
Yes these are functionally the same. Use whichever one seems more intuitive to you.
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.
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I started JavaScript programming last month, i know basic syntax like objects, functions, class, string, array, property. Now i was puzzled on given syntax.
Syntax:
(function(){
"use strict";
})();
My question is, why two parenthesis( one contains 'function' and another "empty" ) are included in the definition? can some one help me why we use this?.
That will create an anonymous function and then immediately execute it.
In this case that function has a single line..."use strict".
That code doesn't have any net impact on the world. What happens is:
The parenthesized function is instantiated;
The final () cause that function to be called;
The "use strict" constant turns on "strict" mode;
The function returns.
What you have there is a self-invoking function.
It pretty much is exactly that, a function which immediately gets called. To accomplish that, we need a function expression, not a function declaration. To achieve that, we can do certain things, one of those is, to put the whole expression in parenthesis
(function() {});
this statement creates a function expression. Now all we have left to do is, to invoke that function by appending additional function parenthesis, like we would do with any function
(function() {})();
You can also put the function parenthesis into the whole statement, it makes no difference
(function() {}());
Another option to bring a function into an expression form is by using ! or + signs infront of it
!function(){}()
Anything goes, as long we create an expression, we can't invoke a function declaration like that
function foo(){}() // syntax error
This is a self-invoked anonymous function (or immediately invoked function expression, also known as IIFE), a pattern that in this case exists just to produce a closed scope.
Apparently, they don't want "use strict"; turning on strict mode for the whole file, or when minified and concatenated to other files, turning on strict mode on included libraries, etc. Amazon had a problem with this a while back. Since then, it's been recommended best practice to keep "use strict" in function scope, and this function exists solely for that purpose.
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.
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.
I'm using JSLint to verify most of my external Javascript files, but the largest amount of errors I'm getting is from functions being used before they're defined.
Is this really an issue I should worry about?
It seems Firefox, IE7 and Chrome don't care. Functions like the popular init() (which I use often) normally stick at the top as that makes sense to me (I like to pretend it's analogous to main()) will, according to JSLint, need to be pushed to the bottom of the file.
As this is the top rated google hit and other people might not be seeing it at first in the jslint tool, there is a option called "Tolerate misordered definitions" that allows you to hide this type of error.
/*jslint latedef:false*/
If you declare functions using the function keyword, you can use them before they're declared. However, if you declare a function via another method (such as using a function expression or the Function constructor), you have to declare the function before you use it. See this page on the Mozilla Developer Network for more information.
Assuming you declare all your functions with the function keyword, I think it becomes a programming-style question. Personally, I prefer to structure my functions in a way that seems logical and makes the code as readable as possible. For example, like you, I'd put an init function at the top, because it's where everything starts from.
If you're using jshint you can set latedef to nofunc, which will ignore late function definitions only.
Documentation - http://www.jshint.com/docs/options/#latedef
Example usage:
/* jshint latedef:nofunc */
noop();
function noop() {}
Hope this helps.
From jslint's website (http://www.jslint.com/lint.html), you can read about a /*global*/ directive that allows you to set variables that are assumed to be declared elsewhere.
Here is an example (put this at the top of the file):
/*global var1,var2,var3,var4,var5*/
The :true :false is not actually needed from my experience, but it looks like it's recommended from what I read on the site.
Make sure the initial global statement is on the same line as /*, or else it breaks.
To disable this warning in jshint for all files, place this in your .jshintrc file:
{
"latedef": false
}
In your .jshintrc file, set:
"latedef": "nofunc",
it is very unfortunate the latedef option was removed. This is essential when trying to create a 'class' with an interface at the top, ie,
function SomeClass() {
var self = this;
self.func = func;
function func {
...
}
}
This style is very common but does not pass jsLint because func is 'used' before being defined. Having to use global for each 'member' function is a total pain.
You can always declare the offending function at the top
eg:
var init;
.... but then you'll have to remove the "var" when you get to the true definition further down:
init = function() {
};