What is benefit of using (function(){...})() in JavaScript - javascript

I noticed in JQuery that the following code structure is used
(function(){var l=this,g,y=l.jQuery,p=l.$,...})()
Which seems to create a function, and call it.
What is the benefit of taking this approach versus having the contents of the function inline?

It creates a closure to prevent conflicts with other parts of code. See this:
http://docs.jquery.com/Plugins/Authoring
Particularly handy if you have some other library that uses the $() method and you have to retain the ability to use that with jQuery also. Then you can create a closure such as this:
(function($) {
// $() is available here
})(jQuery);

It creates a scope for variables, in particular defining $ for example to bind to jQuery, no matter what other libraries overwrite it. Think of it as an anonymous namespace.

With self invoking anonymous function you create a local scope, it's very efficient and it directly calls itself.
You can read about it here

It's just like:
var foo = function(){var l=this,g,y=l.jQuery,p=l.$,...};
foo();
But more simple and do not need a global variable.

It allows to have local variables and operations inside of the function, instead of having to transform them to global ones.

Related

What is the use of passing global variables to functions through arguments in javascript?

I see some self executing function, where the global variable is passed as an argument, even though the global variables are accessible inside the function.
var MyApp = {};
(function(app) {
//Do something with app varaible.
})(MyApp);
is there any reason to pass them to the functions through arguments?
Function arguments, as well as variables declared with var inside the scope of the function, are scoped locally and shadow any values for the same variable in outer scopes.
In your example, this allows $ to have a value outside of the function, and it is only temporarily switched to the jQuery object while inside the function.
$ = "stuff";
console.log($); // "stuff"
(function($) {
console.log($); // the jQuery object
})(jQuery);
console.log($); // "stuff"
Considering your initial code with jQuery:
Is just to help writing code, some programmers get addicted to the $ so they pass the jQuery as arguments and call it $. That code is a better way of doing this $=jQuery, in codes where other frameworks already user $, $=jQuery would overwrite other API code... You typically see that kind of code construct when you use jQuery along with other conflicting libraries that forced you to call jQuery.noConflict().
jQuery.noConflict() removes you the $ functions where you previously were able to do this $('div')... so to keep using $ as before, in code where you know that $ should mean jQuery then you declare code like:
(function($){
...
})(jQuery);
About the closures in general:
This is useful in other cases, imagine you have huge function working using the jquery $ variable and then you add a library to your project that conflicts with $, the closure above would help you in not re-write the code, you could wrap it inside the closure an user $ inside.
Just one more thing, for clearness, (function(){})() is called a closure because you declare an anonymous function an then you execute it, which means you create a private context inside that function.
link about closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
The why for passing globals as parameter to closures, is because when you pass the globals as parameters to locals you rename that global to another name inside of the closures context only. This is a controlled way of saying "hey here jQuery is called $ and jQuery".

Self-invoking function and params?

I've seen the next way of writing self-invoking functions:
(function (app) {
app.foo = {
bar: function(){}
};
}(App));
Where App is a global object.
I wonder, why do we need to pass App as a param into a function? Why don't just use this:
(function () {
App.foo = {
bar: function(){}
};
}());
I see only one advantage of using the first way. If we for some reason rename the App object, then we can easily rename the param in brackets and our code will work as it works. But in case of the second way we will probably need to rename App in all places where we use it.
Are there other differences?
It means that the contents of the function – with regards to the app identifier – are agnostic to the global (or parent) scope.
One of the scenarios in which this is done is, for example, with jQuery, when you don't want to assume that the jQuery object is called $ (e.g. if no-conflict mode is on), but you do want to call it by that name. Passing it through an anonymous function like this (i.e. (function($) {})(jQuery)) allows you to generate a locally-scoped alias that doesn't interfere with the external meaning of the name $ in the parent/global scope.
The other answers explain the benefit of having a locally scoped copy. There are a few other benefits too:
As a micro-optimization it reduces scope lookups (it's less expensive to find a local var than a global one).
It can help in the minification process as all your params are reduce to single letter named vars.
It gives you a pseudo dependency management technique...in your example, you know your code is dependent on App.
For example, many libraries use the "$" character as a shortcut for their main function (e.g. JQuery). This is convenient, but can cause a clash when using multiple libraries. So, you could pass JQuery in like this:
(function($) {
// Code
var nav = $('#nav');
// More code
})(JQuery);
That way, you can still use the convenient shortcut, but you can also avoid clashes (as long as you also configure the libraries not to use the "$" shortcut).
You can also use it to redefine global variables locally to ensure they contain whay you expect:
(function($, undefined) { ... })(jQuery);
Where undefined is now the expected undefined. Also see: What is the purpose of passing-in undefined?
Most other uses are well covered in the other answers.

What is this unknown JavaScript syntax?

Is this jQuery code
(function(jQuery){
})(jQuery);
equivalent to
$(document).ready(function () {
});
If yes, what are the differences between the two? If not, what does the first do?
EDIT:
Thanks everybody. Most response are similar with different flavours and sample
They are not equivalent.
Your first example is an Immediately-Invoked Function Expression (IIFE). It creates a closure around locally defined variables.
Your second example specifies a function to execute when the DOM is fully loaded. It is used to ensure that all element nodes in the DOM are available before executing the enclosed code. This is also a closure.
Both examples use anonymous functions.
It is worth pointing out that it is good practice to use both of your examples, like so:
(function($){
// locally-scoped, DOM-is-NOT-Ready-code here.
$(function () {
// your locally-scoped, DOM-is-ready-code here.
});
}(jQuery)); // note that I've moved the invocation into the parens
// that contain the function. This makes JSLint happy!
Absolutely not, the first one is a self-executing anonymous function and the second is the ready handler.
(function(jQuery){
//jQuery in this scope is referencing whatever is passed-in
})(jQuery);
So, the jQuery inside of the function isn't necessarily the same jQuery outside the function. But you typically do not want to mix-n-match global variable names with local ones.
Take this example:
(function(obj) {
alert(obj);
})('Hello');
This defines a function, then immediately invokes it, passing in "Hello"
$(document).ready(function () {
});
is equivalent to this:
$(function() {
});
The first snippet is an immediately invoked anonymous function which creates a local scope:
(function() {
var x = 2;
})();
alert(x); // undefined
No. The first one isn't really doing much. Just separating any variables inside from the surrounding scope, and creating a local jQuery variable inside.
The second one passes a function that is run after the DOM is ready (in other words after the <body> has loaded).
A common equivalent to:
$(document).ready(function () {
});
is:
$(function () {
});
which does the same thing.
While this:
(function(jQuery){
})(jQuery);
is often written as:
(function($){
})(jQuery);
so that the $ variable is no longer a global variable. Useful if the global $ variable is already in use.
Not at all. The first one is a closure - a function that you create and then immediately call. However, typically you would combine the two like this:
(function($) {
// use the $ variable
$(document).ready(function(){
// ...
});
})(jQuery);
By creating the closure you are renaming "jQuery" to "$" just locally for that block of code. The reason why you use the closure syntax is so that you can use the $ variable even though it might not be defined as a jQuery object in the global scope (i.e. some JavaScript frameworks like prototype use $ as a variable).
Whenever you write a jQuery plugin you should enclose all jQuery code in this kind of closure so it doesn't interfere with any other JavaScript frameworks. If you aren't writing plugins and you don't use any other JavaScript frameworks you probably don't have to bother enclosing your code in a closure.

Why use the javascript function wrapper (added in coffeescript) ".call(this)"

When I use the latest (1.0) release of coffee-script, a simple javascript output looks like this (by default):
(function() {
var a;
a = 1;
}).call(this);
What does .call(this) do and what would be the reason to add it?
It's a way to make sure that the compiled CoffeeScript has its own scope for variable names. This has benefits in terms of efficiency and simplicity (you know you the generated JavaScript won't stomp on variables used by other code). You can disable it with the --bare (or -b) option to the CoffeeScript compiler.
The reason for the call(this) is just to ensure that the CoffeeScript has the same this as the scope where it's placed, because functions don't normally inherit their this object from the surrounding context.
It's creating a function and then calling itself with the parent function/objects scope.
.call and .apply are different methods of invoking a function. You basically created a function that does nothing except set a=1 within its own scope.
In javascript you need to realize that every function is a object, and this is what refers to the current object/function. Using .call(this) overrides this from within the function and replaces it with the one from the calling context.

JavaScript: global scope

Nowdays, i create a .js file with a lot of functions and then I link it to my html pages. That's working but I want to know what's the best way (good practices) to insert js in my pages and avoid conflicts with scope...
Thank you.
You could wrap them in an anonymous function like:
(function(){ /* */ })();
However, if you need to re-use all of the javascript functions you've written elsewhere (in other scripts), you're better off creating a single global object on which they can be accessed. Either like:
var mySingleGlobalObject={};
mySingleGlobalObject.someVariable='a string value';
mySingleGlobalObject.someMethod=function(par1, par2){ /* */ };
or the alternative, shorter syntax (which does the same thing):
var mySingleGlobalObject={
someVariable:'a string value',
someMethod:function(par1, par2){ /* */ }
};
This can then be accessed later from other scripts like:
mySingleGlobalObject.someMethod('jack', 'jill');
A simple idea is to use one object that represents your namespace:
var NameSpace = {
Person : function(name, age) {
}
};
var jim= new NameSpace.Person("Jim", 30);
The best way is to create a new scope and execute your code there.
(function(){
//code here
})();
This is best used when the global scope is accessed at a minimum.
Basically, this defines an anonymous function, gives it a new scope, and calls it.
It's perhaps not the BEST way, but a lot of PHP systems (I'm looking at you, Drupal) take the name of their particular plugin and prepend it to all their function names. You could do something similar, adding the name of your capability to your function names - "mything_do_action()"
Alternately, you could take a more "OO" approach, and create an object that encapsulates your capability, and add all your functions as member functions on IT. That way, there's only one thing in global scope to worry about.

Categories