JavaScript notation: (function() { ... } )(); [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
Hello all,
I have seen several JavaScript files using this notation:
Start of JavaScript file:
(function() {
// All functions go here.
// Can someone say what the wrapping nameless function is used for?
})();
Also with the prototype library, this seems possible:
function $() {
// Prototype $-wrapping function.
}
Can someone please explain the above two code fragments, their uses and their differences? Some keywords which would help me find more about this notation/technique (how it is named) would be helpful too so I can run a Google search on it... :)
Thanks!

In your first example, people surround their code in an anonymous function for scoping reasons, to avoid global namespace cluttering. That weird parentheses syntax is used to define and execute the function all in one step; the () at the end has the meaning of executing the function itself.
So inside that anonymous function you could define function apple(){} and it would only be accessible inside that anonymous function. This is good if you're making a library and want only certain things to clutter your global namespace.
Your second example is just a simple function called $. Many libraries like to use this name because it's short and concise, and since you need to type it every time you want to reference the libraries namespace, the shorter, the better.

I searched for "javascript wrapping function" and the first hit was this, which says:
This method doesn't add any new symbols to the global or LIB spaces.
I don't understand the second part of the question: function $() { ... } isn't a "nameless" function: it has the name $! If you like functions named $ it's the most straightforward way I know of to make such a thing.

An annonymous function is defined
function() {
}
and then immediately called
()
The extra () enclosing the function is to force the interpreter to treat the function as an expression. Javascript treats any statement starting with the function keyword as a declaration so it could not otherwise be immediatly called.
The purpose is to avoid polluting the global namespace. All variables defined in the function will be local to the function.
Google for module pattern.

retracted in favor of answer to: What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

First one is called immediate function. You can read more about this function pattern here.

Related

Why does Javascript syntax use multiple parentheses? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 7 years ago.
The code below is supposed to declare a new module:
(function() {
'use strict';
angular.module('app.avengers', []);
})();
Due to my unfamiliarity with javascript, I am struggling to understand why the multiple parenthesis.
I realize this might be a silly question, but just seeking to understand why it was written this way instead of just:
angular.module('app.avengers', []);
The syntax you are getting confused with is an anonymous function.
The reason for the anonymous function ((function() {...})();) is to restrict the scope of 'use strict' to the function. If you had that code outside of the function, it would apply to the global scope, which isn't desired.
More information on strict mode here: http://www.w3schools.com/js/js_strict.asp
This function is declared in an alternative JavaScript Design Pattern called "Immediately Invoked Function Expression", or more commonly, IIFE.
Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.
This isn't necessary for Angular apps, but it is a common practice used by many JavaScript developers.
The first set of Parenthesis enclose the entire function block as an anonymous function. The second, empty parenthesis serve to invoke the anonymous function, hence the common confusion that it is "self executing". In essence, the anonymous function performs the task of defining the inner function, then the invocation ensures the definition is actually processed.
As others have stated, the main reasons to define a function in this manner is to isolate the code, and to ensure that 'use strict'; is only applied to the function, not the global scope. Though, in this limited example, the pragma 'use strict;' is serving a very limited purpose.
That's what's called a immediately invoked function expression in javascript, and it's not related to angular JS.
The first set of parens gives you an enclosed lexical scope, and returns the function object defined within, and the second set of parens executes the function.
So simply:
define
execute
(function() {
...
}}();
is a "self-executing anonymous function" (EDIT: or more correctly, "immediately invoked function expression"). It defines a function: function() { ... }, then executes it with no arguments (()). It is functionally equivalent to the following, which may be easier to follow:
var temp = function() {
...
};
temp();
This serves to isolate the code in the function in a local environment, making any variables in it invisible to the outside world.
In this case, it serves to isolate the pragma directive use strict.

JS: What's the difference between a ! closure and () closure? [duplicate]

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 want to know about this javascript function pattern [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does this “(function(){});”, a function inside brackets, mean in javascript?
javascript anonymous function
(function())()
this is used in many js library like jquery,YUi
Thats called Module Pattern. The idea is to have an encapsulated module, that cannot conflict with any other modules you or someone else has created. You can create public and private methods within that module.
See: Js Pattern
I'm not sure what (function())() means, but I'll work on the assumption that you meant (function() { … })(). It is roughly the same as:
f = function() { … }; // Define a function.
f(); // Call it.
The only difference is that it does so without requiring a variable.
It is an anonymous self executing function. It is anonymous, because it is not named, and self executing, so it runs (there would be no other way to run an un-named function).
It is particularly useful to enclose a discreet module of code, because it acts as a closure preventing variables leaking into the global namespace.
You're immediately calling an anonymus function with a specific parameter.
An example:
(function(name){ alert(name); })('peter') This alerts "peter".
In the case of jQuery you might pass jQuery as a parameter and use $ in your function. So you can still use jQuery in noConflict-mode but use the handy $:
jQuery.noConflict() (function($){ var obj = $('<div/>', { id: 'someId' }); })(jQuery)
It simply executes the code wrapped in parentheses right away (the first block returns a function, the second pair of parens executes it).
Take for instance these two snippets:
function foo() {
print 'foo';
}
(function() {
print 'foo';
})();
The first won't do anything until you call foo(); whereas the second will print 'foo' right away.

standalone parentheses in javascript [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
JavaScript: Why the anonymous function wrapper?
A Javascript function
How does the (function() {})() construct work and why do people use it?
I saw some code in javascript in following format :
(
function()
{
//stmt
}
)();
Why exactly do we use these standalone parentheses? Thank you.
This code creates a function expression, then calls it immediately.
It's the same as
var unnamed = function() { ... };
(unnamed) ();
The last two parantheses before the ; execute the anonymous function directly. The other two parantheses are optional and just some sort of convention.
This pattern is commonly used for not polluting the global namespace:
(function() {
var a = 42;
})();
alert(a); // a is undefined
Paul Irish has a pretty good screencast about this and other javascript patterns: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/
This is the basis for what is called the Module pattern in Javascript. See these articles for more information:
http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
http://yuiblog.com/blog/2007/06/12/module-pattern/
Essentially, as the articles state, this pattern is perfect for maintaining privacy and state, but also allow loose coupling and chaining of your Javascript modules.
The standalone parentheses () means to execute the function, in this code, it's a anonymous function.
Creates annonymous function and calls it, therefore avoiding pollution of the namespace and memory for functions that are called only once.
Although similar to:
var f = function () { ... };
f();
This variant avoids creating a variable f, which saves memory and avoids namespace conflicts.

What is this practice called in JavaScript?

When you wrap your JavaScript code in a function like this:
(function(){
var field = ...;
function doSomthing(){...
...
})();
I noticed that this fixes scoping problems for me on a lot of web pages. What is this practice called?
The pattern is called self-invocation, a self-invoking function. It can create a closure, but that is an effect of the pattern (perhaps the intended effect), not the pattern itself.
To clarify a bit for the comments below, most of the time it's creating a closure, it keeps your variables scoped to that local closure, as to not create global variables, it both keeps things clean and avoids any potential unwanted changes to those variables.
There are some excellent answers here that explain the why a bit more: How does a javascript closure work?
It's only a creating closure when something inside that scope is exposed to an outer scope, which is usually the case, but I can't be sure for your example without seeing more code. If nothing is exposed then no closure's created...otherwise it's just an anonymous function executing immediately.
The })(); format at the end, as opposed to }); is actually calling that closure to execute immediately, with no parameters. If you had something in it, for example })(something); then that something would be passed as the first argument here: (function(somethingParam){.
The wrapping function is called an anonymous (it has no name and it isn't assigned to a variable) self-executing (it executes immediately, by itself) function.
I don't remember seeing an exact name for this pattern, but it prevents variable from leaking into global scope.
Ben Alman presents an interesting argument on the commonly use terminology for this "pattern".
His blog post about it is here (http://benalman.com/news/2010/11/immediately-invoked-function-expression/).
If his post is too long for you here is my summary (I still recommend reading it as this summary leaves out a lot):
If you want a named function to be self executing/invoking it would should look like this:
// Hello, my name is "foo". I am a named function.
// When I am invoked I invoke my self when I am invoked.
function foo(){
foo();
}
If you want an anonymous function to be self executing/invoking it should look like this:
// Hello, I have no name...
// (though I am assigned to the variable "foo" it's not who I am).
// When I am invoked I invoke my self when I am invoked.
// In ECMAScript 5 I no longer work. :-(
var foo = function(){
arguments.callee();
};
If you want an anonymous function to be immediately executed/invoked it should look like this:
// Hello, I have no name. I am immediately invoked.
// People sometimes call me a "self-invoking anonymous function"...
// even though I don't invoke myself.
// Ben Alman calls me an "Immediately-Invoked Function Expression"...
// or "iffy" for short.
(function(){ /...code.../ }());
My own thoughts on the matter:
The other answers are correct; what you are asking about is commonly referred to as a "self invoking anonymous function."
However, that terminology doesn't accurately reflect what is really happening; "Immediately-Invoked Function Expression" (aka "iffy", for short) seems like a more appropriate term.
Fun facts to impress your friends:
You can create an Iffy like this, too:
!function(){
alert("immediately invoked!");
}();
or
+function(){
alert("immediately invoked!");
}();
or if you are really cRaZy ( example ):
!1%-+~function(){
alert("immediately invoked!");
}();
in most browsers (if not all, I'm not sure) and the effect will be the same (facebook uses the ! version).
Douglas Crockford and the YUI team call it the module pattern.
What is this practice called?
It's called an immediately-invoked function expression, in short: IIFE. It defines a function in an expression, which is then executed on its own (without assigning the function to any identifier). It sometimes is also called immediately executed function expression (IEFE).
Before Ben Alman wrote his blog post on them, they were also known as self-invoking (anonymous) functions, a term which became uncommon since then. It was technically imprecise, hinting at a recursive invocation which does not actually happen.
For details on the syntax see Explain the encapsulated anonymous function syntax and Location of parenthesis for auto-executing anonymous JavaScript functions?.
I noticed that this fixes scoping problems for me on a lot of web pages.
Yes, the purpose of this pattern is to introduce an extra scope by executing a function.
The pattern also is sometimes extended with a return value, known as the (revealing) module pattern, or with a name for the function to allow recursive invocations.
It's been around longer than "patterns". It is a common idiom in scheme/lisp primarily used for encapsulation especially when doing meta programming.

Categories