I've been playing around with Node.js after having not used JavaScript for a long time.
One thing I've noticed is that many of the sample files I've been looking at use the following convention:
(function() {
... all javascript code for the file ...
})();
Is there a reason to enclose all the JavaScript in a file in a function like that, or is it just convention? Is it something I should mimic?
I should also note, that at least in the files I've been playing with, the code works the same way with or without the function surrounding everything.
Thanks for your insights!
Variables in Javascript have function scope. You're wrapping your code in a function in order for it not to clobber the global namespace with tons of variables, which may lead to bugs later on when different code is added. E.g.:
// module 1
(function () {
var foo = 'bar';
...
})();
// module 2
(function () {
var foo = 'baz';
...
})();
No problems, because both modules have their own variable scopes.
Maybe its better to refer you to some good resources
related topic in stackoverflow
What are the benefits of a closure, and when are they typically used?
some detail explaination
http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/
or more:
search result from stackoverflow
https://stackoverflow.com/search?q=javascript+closure
recently given answer on the same. This is an anonymous function which will execute its body.
So when the file containing this code loads all the logic inside this function is self executed.
(function() {
alert('hi');
})();
try writing this and executing. Also you can have your variables inside the scope of this function so that they do not interefere with a global scope and bring up errors when used with other javascript libraries.
It creates a scope, so it is useful for information hiding and not polluting the global object.
Related
What are the benefits of using self executing functions with a framework, such as, Angular?
I am new to Angular but my understanding thus far is the module-based design gives most of the benefits that the Self executing function gives. What am I missing? Is it just a matter of style?
Here is an example by Ben Nadel. I really like the style but want to understand if there are any gains by writing Angular code this way or if it is mostly a style choice.
Mainly, it ensures that your code is not declared on the global scope, and any variables you declare remained scoped within your function.
In this case, it also has the benefit of declaring the objects required to run the code in one place. You can clearly see at the bottom that the angular and Demo objects are passed in, and nothing else. If the code was not wrapped in the function, you'd have to scan through the code to see what the dependencies were.
Personally, I prefer to use a module loader like RequireJS, which effectively forces you to follow this pattern.
That's kind of a opinion question. The main advantage I see on self executing functions is to not create global variables. I had never seen this pattern with angular.
On the example link you gave, it does not seem to have any advantage. The angular variable will exist anyway on a angular application, so you could use angular directly. And the Demo being a module, you can add controllers to it without without messing with the global scope.
I like a lot of self executing functions. But in this case I really don't see an advantage.
Daniel, you said: "if it is mostly a style choice".
I know at least two examples in javascript when "code style" is not only matter of preference but it causes different result.
Are semicolons optional? Not at all.
$scope.test = function() {
console.log('Weird behaviour!')
} //; let us comment it
(function() {} ()); //two functions seem to be independent
is equal to
$scope.test = function() {
console.log('Weird behaviour!')
}(function() {} ()); //but without semicolon they become the one
Another example of "code style" which is not related to self-executing functions:
var x = (function() {
return //returns undefined
{};
}());
alert(x);
/*
that is why, I suppose, while writing javascript code,
we put function brackets in the following "code style":
function() { //at the same line
return { //at the same line, this style will not lose the object
};
}
*/
Code style formation is dictated by unexpected results of such kind.
Last but not least.
With selfexecuting function: a closure is created on function call and keeps your vars local.
A closure is created on function call. That is why self-executing function is so convenient. As Daniel correctly mentioned it is a good place for keeping an independent code unit, this pattern is called module pattern. So when you move from pure javascript to specific framework or vise versa this independence enables code changes to be more fluid. The best case is just moving your module to an angular wrapper and reusing it.
So it is convenient for the purpose of code transmission from one technology to another. But, as I believe, it does not really make sence for specific framework.
I see in a lot of scripts this pattern
(function(){})();
What is it and why use it?
It's used to force the creation of a local scope it avoid poluting the current (often global) scope with the declarations.
It could be rewritten like this if you want to avoid the anonymous function :
var scope = function() { /*...*/ };
scope();
But the anonymous function syntax have the advantage that the parent or global scope isn't even poluted by the name of the function.
(function() { /*...*/ })();
It's also a good way to implement information hiding in javascript as declarations (functions and variables) in this scope won't be visible from the outside. But they could still see each other and as javascript implement closures functions declared inside such a scope will have access to other declarations in the same scope.
That is defining a function with no name, and immediately calling it. Because Javascript functions act as closures -- a persistent scope -- this is a useful way to create a set of interconnected objects or functions.
An anonymous function is a function (or a subroutine) defined, and possibly called, without being bound to an identifier.
This is the basic syntax for creating a closure. More typically, it'd contain some code:
(function(){
//Your Code Here
})();
This is equivalent to
var some_function = function() {
//Your Code Here
};
some_function();
The biggest reason for doing this is cleanliness; any variables declared outside of any function are global; however, variables declared inside of this function are contained inside of this function and won't affect or interactive with any code outside of the function. It's good practice to wrap any kind of reusable plugin in a closure.
It's immediately executing anonymous function.
It's basically the same as:
var test = function(){};
test();
but does not require usage of additional variable.
you need to wrap it in additional parenthesis to get the function as a result of your expression - otherwise it's understood as function declaration, and you can't execute a declaration.
it's mostly used for scope protection - because JS has functional scope, every variable defined as var x; inside such function will be kept in it's function local scope.
all of this simply means 'immediately execute everything inside this function without polluting the global scope'.
it's also commonly used in well known patterns, such as module pattern and revealing module pattern. please see http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth for more detail.
It is called an immediate function or an anonymous closure and is the basis of the module pattern.
It is used to create a private local scope for code.
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.
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.
I'm pretty new to JavaScript, which I am learning on my own. I'm currently creating and tweaking GreaseMonkey scripts. I've noticed that most simple scripts (i.e. those with no need for named functions) go straight into the main code, but some instead are set up like this:
(function() {
//main code here
})();
What is the significance of this type of coding? I've commented out both the top and bottom, and the script still runs exactly the same.
Is it just a coding standard, or does it actually have a function? And, as my title asks, is it something specific to GreaseMonkey, or something that I should do all the time?
This technique effectively creates a private namespace, accessible only to this script. For example, this code:
(function() {
var a = 5;
})();
will have no effect on the global namespace (the a variable is captured by the closure, so window.a will not be affected). It's a very nice way to keep many scripts from stepping on each other's global variables, by making them not global at all. I use this technique all the time when writing any JavaScript, not just Greasemonkey scripts, and would strongly recommend it as a best practice when writing libraries.
If you wanted to expose some functions to other JavaScript code instead of completely isolating your script, you could do something like this:
var MyNamespace = (function () {
var that = {};
that.square = function(x) {
return x*x;
};
return that;
})();
Then you could do MyNamespace.square(5) from another script, and this would return 25.
It's a self executing anonymous function.
It's usually used to change the scope, all variables/functions declared inside this will be in the anonymous function's scope instead of the global (window) scope.
The code serves two purposes:
It keeps objects/variables local to the anonymous function scope. This is important as we see that you may have several script files that all might share the same variable name. If they did, they could replace the variables value and truly muck with your application.
The () at the the end of the line calls the declared function. In other words, the anonymous function you created inside the first set of parentheses can automatically be called instantly. Unless you assigned it to a variable, there would be no other way to call it. This avoids creating a variable in memory and just calls the function at runtime.
Here's the answer for those who never heard of the word closures:
Suppose we have a function
function sayHi() { alert('Hello'); }
We would call this function by doing this:
sayHi();
The above is whats called a named function, if you don't know what that means, then it's what you think of when you hear the word function
In some languages you don't have to name a function, you can leave it blank like so:
alert('Sup');
function() {alert('Hello'); }
3 + 1;
alert('Peace');
Line 2 is perfectly valid. Of course line 2 won't really do anything in your page, just like line 3 doesn't do anything. That is called an anonymous function. Now just like we can assign a variable to line 3 like:
result = 3 + 1;
We can do the same with line 2, like this:
myFunc = function() { alert('Hello'); };
And we can use myFunc as a function like the sayHi() function before. We call it just like we call sayHi()
sayHi();
myFunc();
Now since javascript is written to be versatile, where stuff like [0, 1, 2].indexOf(1) works, we can do the following:
func = function() { alert('hello'); };
func();
(function() { alert('hello'); })();
And line 1 & 2 will accomplish the same thing as line 3 since line 3 is just an expanded version of line 1 and 2. The advantage of line 3 is that if someone later on in the code uses a func variable it wouldn't cause a problem with your own code, also any variables declared in line 3's function (with a var keyword) won't be a valid variable outside of your function, which in this case is what a closure is.
Well that's it for this micro-tutorial, hope it helps.