standalone parentheses in javascript [duplicate] - javascript

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.

Related

Is there any difference in this JavaScript code? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 6 years ago.
I have seen various code which is implemented in following two way. I always use the second one (2.). I wanted to know two thing here.
Is there any difference between these two codes?
Which one is the best practice (and why) if any?
1.
(function () {
//some code here, angular code
})();
2.
(function () {
//some code here, angular code
});
Please also suggest me some good blog or book in this regards as I wants to learn in more detail. Thank you all advance..
Yes, you are not executing the second one.
In the first example, you are declaring an anonymous function, which gets run afterwards with no parameters.
In the second example, you are just declaring it, but not running it.
() is what makes it run, in this case by passing it no parameters.
This one executes the anonymous function:
(function () {
//some code here, angular code
})();
This one doesn't execute it:
(function () {
//some code here, angular code
});
For example, if you have a parameter, you can pass it like so:
(function (c) {
// c.log() is same as console.log
c.log("hello");
})(console);
Note: I've added the parameter example because it's less obvious without any parameter.
Edit:
As #Osman has just pointed in the comments, the first one is known as IIFE.
This pattern is so common, a few years ago the community agreed on a
term for it: IIFE, which stands for Immediately Invoked Function
Expression.
The second is declaration, the first is declaration and execution.
Difference:
The first one executes the anonymous function expression:
(function () {
//some code here, angular code
})();
The second one doesn't execute it:
(function () {
//some code here, angular code
});
anonymous function is a function that doesn't have a name.
Background:
Basically, first we are wrapping the anonymous function declaration with first brackets, like: (), to make it a function expression:
// this is a function declaration:
function () {
//some code here
}
// this is a function expression
(function () {
//some code here
});
By itself it does nothing, as we are neither executing it, nor declaring it within the current scope. In other words, it's useless. Learn more about the difference between function declaration & function expression.
Now, we can use the function expression as a parameter to some other function, like jQuery does:
// now jQuery is taking the function expression as parameter
$(function () {
//some code here
});
Or, we can execute the function itself by using () at the end (This is how we invoke any function actually - in this case without any parameter):
// Now the function expression gets executed.
(function () {
//some code here, angular code
})();
This is also known as Immediately-Invoked Function Expression or IIFE.
The above examples don't have any parameter. However, if you have a parameter, you can pass it like so while executing:
(function (c) {
// Here c.log() is same as console.log()
c.log("hello");
})(console);
Note: I've added the parameter example because it may be less obvious without any parameter.
Best Practice:
Since functionally they are different, the question of best practice doesn't appear. Usually we use IIFE in cases where we want to execute something in a scope different from the current scope & we don't want to leave any footprint of function declaration, variable declaration etc. within the current scope.
Further Reading:
More discussion about this can be found in the following links:
What is the (function() { } )() construct in JavaScript?
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
What is the purpose of a self executing function in javascript?
You Don't Know JS: Scope & Closures.
The first one is an IIFE (Immediately-invoked function expression ) as others said, for more info on IIFE check this repo by Kyle Simpson (author of You don't know JS)

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.

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.

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

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.

What do parentheses surrounding an object/function/class declaration mean? [duplicate]

This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 8 years ago.
In the YUI library examples, you can find many uses of this construct:
(function() {
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event,
layout = null,
...
})();
I think the last couple of parentheses are to execute the function just after the declaration.
... But what about the previous set of parentheses surrounding the function declaration?
I think it is a matter of scope; that's to hide inside variables to outside functions and possibly global objects. Is it? More generally, what are the mechanics of those parentheses?
It is a self-executing anonymous function. The first set of parentheses contain the expressions to be executed, and the second set of parentheses executes those expressions.
It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.
See:
http://en.wikipedia.org/wiki/Closure_%28computer_science%29
http://peter.michaux.ca/articles/javascript-namespacing
Andy Hume pretty much gave the answer, I just want to add a few more details.
With this construct you are creating an anonymous function with its own evaluation environment or closure, and then you immediately evaluate it. The nice thing about this is that you can access the variables declared before the anonymous function, and you can use local variables inside this function without accidentally overwriting an existing variable.
The use of the var keyword is very important, because in JavaScript every variable is global by default, but with the keyword you create a new, lexically scoped variable, that is, it is visible by the code between the two braces. In your example, you are essentially creating short aliases to the objects in the YUI library, but it has more powerful uses.
I don't want to leave you without a code example, so I'll put here a simple example to illustrate a closure:
var add_gen = function(n) {
return function(x) {
return n + x;
};
};
var add2 = add_gen(2);
add2(3); // result is 5
What is going on here? In the function add_gen you are creating an another function which will simply add the number n to its argument. The trick is that in the variables defined in the function parameter list act as lexically scoped variables, like the ones defined with var.
The returned function is defined between the braces of the add_gen function so it will have access to the value of n even after add_gen function has finished executing, that is why you will get 5 when executing the last line of the example.
With the help of function parameters being lexically scoped, you can work around the "problems" arising from using loop variables in anonymous functions. Take a simple example:
for(var i=0; i<5; i++) {
setTimeout(function(){alert(i)}, 10);
}
The "expected" result could be the numbers from zero to four, but you get four instances of fives instead. This happens because the anonymous function in setTimeout and the for loop are using the very same i variable, so by the time the functions get evaluated, i will be 5.
You can get the naively expected result by using the technique in your question and the fact, that function parameters are lexically scoped. (I've used this approach in an other answer)
for(var i=0; i<5; i++) {
setTimeout(
(function(j) {
return function(){alert(j)};
})(i), 10);
}
With the immediate evaluation of the outer function you are creating a completely independent variable named j in each iteration, and the current value of i will be copied in to this variable, so you will get the result what was naively expected from the first try.
I suggest you to try to understand the excellent tutorial at http://ejohn.org/apps/learn/ to understand closures better, that is where I learnt very-very much.
...but what about the previous round parenteses surrounding all the function declaration?
Specifically, it makes JavaScript interpret the 'function() {...}' construct as an inline anonymous function expression. If you omitted the brackets:
function() {
alert('hello');
}();
You'd get a syntax error, because the JS parser would see the 'function' keyword and assume you're starting a function statement of the form:
function doSomething() {
}
...and you can't have a function statement without a function name.
function expressions and function statements are two different constructs which are handled in very different ways. Unfortunately the syntax is almost identical, so it's not just confusing to the programmer, even the parser has difficulty telling which you mean!
Juts to follow up on what Andy Hume and others have said:
The '()' surrounding the anonymous function is the 'grouping operator' as defined in section 11.1.6 of the ECMA spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf.
Taken verbatim from the docs:
11.1.6 The Grouping Operator
The production PrimaryExpression : ( Expression ) is evaluated as follows:
Return the result of evaluating Expression. This may be of type Reference.
In this context the function is treated as an expression.
A few considerations on the subject:
The parenthesis:
The browser (engine/parser) associates the keyword function with
[optional name]([optional parameters]){...code...}
So in an expression like function(){}() the last parenthesis makes no sense.
Now think at
name=function(){} ; name() !?
Yes, the first pair of parenthesis force the anonymous function to turn into a variable (stored expression) and the second launches evaluation/execution, so ( function(){} )() makes sense.
The utility: ?
For executing some code on load and isolate the used variables from the rest of the page especially when name conflicts are possible;
Replace eval("string") with
(new Function("string"))()
Wrap long code for " =?: " operator like:
result = exp_to_test ? (function(){... long_code ...})() : (function(){...})();
The first parentheses are for, if you will, order of operations. The 'result' of the set of parentheses surrounding the function definition is the function itself which, indeed, the second set of parentheses executes.
As to why it's useful, I'm not enough of a JavaScript wizard to have any idea. :P
See this question. The first set of parenthesis aren't necessary if you use a function name, but a nameless function requires this construct and the parenthesis serve for coders to realize that they've viewing a self-invoking function when browsing the code (see one blogger's best-practices recommendation).

Categories